Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I store a table within a table and still be able to sort?

I looked into metatables and I'm not sure if I just didn't understand it or if it actually wasn't a viable option for this but if it is either post or comment howso. So I want to store tables within a table that will later be sorted by the first value of the table.

local teamRanking = {}

for _2, v2 in pairs(game.Players:GetChildren()) do
	if v.TeamColor == v2.TeamColor then
		--Removed code
		table.insert(teamRanking, {tonumber(f.Level.Text),f.Name}) -- { Level Value, Player Name }
	end
end

table.sort(teamRanking)

How would I go about fixing this so that the table.sort doesn't break once it tries to compare two table values?

1 comment

0

What criteria would you use to sort them...?

3 answers

✓ Accepted answer

Metatables have nothing to do with this

Super brief description of metatables:

A way to hack into the default operations like one + two or a.b or e[f] = g or x .. y to change their behavior to absolutely anything you want


There's an optional parameter to table.sort which is what to use to compare things.

I'm assuming you're trying to sort these things by their first element, that tonumber value. So that is what we compare by. We can pass an anymous function to table.sort to do this:

table.sort(teamRanking,
	function(one,two)
		return one[1] < two[1];
	end
);
local function PreSort(t,f) local k={} for v in pairs(t) do table.insert(k,v) end
table.sort(k,function(a,b) return f(t[a][1],t[b][1]) end) coroutine.resume(coroutine.create(function() wait(.1) k={} end)) return k end

local List={
{85,"Telamon"};
{77,"chiefjustus"};
{21,"Sorcus"};
{92,"ROBLOX"};
}

local Sort=PreSort(List,function(a,b) return a>b end)

for _,v in pairs(Sort) do
print(List[v][1],List[v][2])
end

2 comments

0

Nothing in here justifies the use of a coroutine (delay would be much better even then).

0

I'm pretty much new to table.sort right now, I managed to make my own dps meter thanks to it, thanks for the correction

I think I understand what you mean.

table = {"1","2"}
table2  = {(table)} -- table in a table

Sort of new to this, so I am most probably wrong.

This discussion is preserved as it was. New answers, comments, and votes are closed.