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

Table.sort are tricky i think, how?

Asked by
gloveshun 119
4 years ago

I tried to make a system what includes table.sort(), but with failure...

table.sort(My_Table, 3)
0
hELLLP Meeh gloveshun 119 — 4y
0
Were gonna need a lot more context than "Its not working" iResioku 15 — 4y
0
? gloveshun 119 — 4y
View all comments (2 more)
0
You need to specify what u want it to do, how it failed, what the error was like, all that information iResioku 15 — 4y
0
You need to inform us of what the error is, be descriptive with the errors and such. It will help us fix this. Just2Terrify 566 — 4y

1 answer

Log in to vote
1
Answered by
Yuuwa0519 197
4 years ago
Edited 4 years ago

As of my knowedge, unless you want a specific way to sort the table you don't need a second parameter as it sorts from smallest to largest by default. However, if you want to sort in a special way such as from largest to smallest, table.sort() requires a function as a second parameter to sort the array. For example, if I have table :

local t = {
    {"Data1", 2},
    {"Data4", 4},
    {"Data0", 0}
}

and if I were to reorder the table from largest to smallest by second value of each table I would have a function that sorts this.

local t = {
    {"Data1", 2},--what I mean by second value is , {"Data1(First Value)",2(Second Value)}
    {"Data4", 4},
    {"Data0", 0}
}


table.sort(t,--the table I want to sort
    function(a,b) --a function to sort the value. by default, it sorts from least to greatest.
    return a[2]>b[2] -- if the second value of "A" is greater than "B" then return true
    end)

for I,v in pairs(t) do
    print(tostring(v[1]).."|"..tostring(v[2]))
end
Ad

Answer this question