Numerically ordering a table of tables

I am attempting to order a set of tables in a table based on a value in those tables.

Example of what I mean:

local storagetable = {}
storagetable[1] = {}
storagetable[1]["points"] = 100

storagetable[2] = {}
storagetable[2]["points"] = 98

storagetable[3] = {}
storagetable[3]["points"] = 4

local newtable = {}

This is not the actual format of the tables but it is the closest visualization that I could come up with.

I am attempting to write a function that will go through the table and place each subtable in the newtable table from largest to smallest based on the subtable.points value.

This is what I came up with and it did not work in the slightest:

function orderresults (tabletoorder)
	local newtable = {}
	for i,v in pairs (tabletoorder) do
local num = 0
	if newtable[tonumber(v.points)] ~= nil then
print(tonumber(v.points))
		while newtable[tonumber(v.points)+num] ~= nil do
			wait() 
			num = num + 1
		print(tonumber(v.points)+num,newtable[tonumber(v.points)+num])
		end
	end
	newtable[tonumber(v.points)+num] = v
	end
return newtable
end

It sounds like you can use table.sort for this. You can pass in a table and a function that does the sorting.

local storagetable = {}
storagetable[1] = {}
storagetable[1]["points"] = 100

storagetable[2] = {}
storagetable[2]["points"] = 98

storagetable[3] = {}
storagetable[3]["points"] = 4

table.sort(storagetable, function(a, b)
    return a.points > b.points -- answers the question "should a come before b?"
end)

If you don’t want storagetable sorted, but you do want a new table sorted, then you can copy the contents to a new table first and sort the new table:

local newtable = {unpack(storagetable)} -- this does a quick shallow copy for arrays
table.sort(newtable, function(a, b)
    return a.points > b.points
end)

I tried this and it only sorted based off of the first number, so say the numbers were 11, 293, and 1, the sort order would end up being 11,1,293.

That means that your numbers are strings, not numbers. That means that your table is actually:

local storagetable = {}
storagetable[1] = {}
storagetable[1]["points"] = "100"

storagetable[2] = {}
storagetable[2]["points"] = "98"

storagetable[3] = {}
storagetable[3]["points"] = "4"

This is something that you should fix. If for some reason you can’t or won’t fix it, here’s a workaround:

table.sort(storagetable, function(a, b)
    return tonumber(a.points) > tonumber(b.points) -- answers the question "should a come before b?"
end)
4 Likes

That was it, thank you for the help!