Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 9 years ago

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?

0
What criteria would you use to sort them...? BlueTaslem 18071 — 9y

3 answers

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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
);
Ad
Log in to vote
0
Answered by
Nymint 85
9 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.
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
0
Nothing in here justifies the use of a coroutine (`delay` would be much better even then). BlueTaslem 18071 — 9y
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 Nymint 85 — 9y
Log in to vote
-1
Answered by 9 years ago

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.

Answer this question