I have the below program code which tries to sort a given list. I have tried various options and it still doesn`t work.
local List = {}
List[143] = "143"
List[145] = "145"
List[120] = "120"
List[178] = "178"
table.sort(List, compare)
compare function is defined as
function compare(a, b)
if tonumber(a) < tonumber(b) then
return true
end
end
Above table.sort does not work to any order. I just want to sort it to increasing numerical order. If you have any ideas about this please help me. Thanks in advance
table.sort
(and much of the rest of the table.*
functions) is defined only for operations on array-like tables. That means tables with contiguous integer keys from 1..n
. Your table doesn't meet those criteria.
The keys of that table do not satisfy requirements of that function. The keys must start at 1 and sequentially increase to N, as per Lua ref manual ("Sorts table elements in a given order, in-place, from table[1]
to table[n]
"). Try
local List = {}
List[1] = "143"
List[2] = "145"
List[3] = "120"
List[4] = "178"
table.sort(List, compare)
or even better
local List = {"143", "145", "120", "178"}
table.sort(List, compare)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With