A table either is a set of key/value pairs or an array. OK, that's not entirely true; a table can be both, but the key/value entries will have no relationship to the array entries. That is, you can do this:
tbl = {
['a'] = 1,
['b'] = 4,
[1] = {'a', 1},
[2] = {'b', 4},
}
tbl[2]
will have no direct relationship to tbl['b']
. You can perform tbl[2] = <anything>
, and it will have no effect on the contents of tbl['b']
.
So long as the table doesn't change, you can take any pure key/value table and build an array part of it, which you can then sort however you like. Here's a function which does that:
local function build_array(tbl)
--We cannot modify `tbl` while iterating through it, so build a temp array.
local arr = {}
for key, value in pairs(tbl) do
arr[#arr + 1] = {key, value}
end
for ix, value in ipairs(arr) do
tbl[ix] = value
end
return tbl
end