Another table.sort thread

Posted by Trevize on Wed 22 Jun 2005 07:10 PM — 3 posts, 21,333 views.

#0
Ok, I know this questions has already been answerd in: "http://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=5514";, and that table.sort is explained here: "http://www.lua.org/manual/5.0/manual.html#5.4"

But I still dont get it, maybe Im an complete idiot or something but how does table.sort work?

This is how my current test.lua file looks like, im trying to figure out how table.sort is working but no mather what I do, I dont get it to work.

afflictions = {
	{ name = "addiction", priority = 8 },
	{ name = "agoraphobia", priority = 7 },
	{ name = "asthma", priority = 6 },
	{ name = "claustrophobia", priority = 9 },
	{ name = "clumsiness", priority = 6 },
	{ name = "confused", priority = 10 },
}

function test1()
	for k, v in afflictions do
		Note("Name: " .. tostring(v.name) .. ". Priority: " .. tostring(v.priority))
	end
end

function test2()
		table.sort (afflictions)
end

The "afflictions" table is "alot" bigger in the real file.

This is my current scripting error message when trying to call function test2:
attempt to compare two table values
stack traceback:
[C]: in function `sort'
[string "Script file"]:20: in function `test2'
[string "Command line"]:1: in main chunk

The main file is alot bigger and more complicated but since I cant event get this one to work I dont see the reason to bring the whole thing up here.

One more thing, this is proberly quite important. In my main file I want to sort a table like:
table1 = {
{ name = "addiction"},
{ name = "agoraphobia"},
}
after the priority stated in table2 where name in table1 is equal to the name in table2.
table2 = {
{ name = "addiction", priority = "8", syntax = "eat nightshade" },
{ name = "agoraphobia", priority = "7", syntax = "eat orphine" },
}
USA #1
Quote:
table.sort (table [, comp])

Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the size of the table (see 5.4). If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.


Pay attention to the part about 'comp'. What Lua is telling you is that it has no way of sorting tables, which makes sense, right, because what does { ... } < { ... } resolve to?

So, you have to give it a function that takes two tables, table1 and table2, and returns true if table1 is considered "less than" (i.e., comes before in the sorting order) than table2.

Back to your case, I don't think there's much use in sorting the first table according to the values in the second. You may as well just sort the second.
Australia Forum Administrator #2
Also see this post:

http://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=6036