Is there any way to loop trough a table like the one below in the same order as it's written?
local tbl = {
["hello"] = 1,
[2] = 2,
[50] = 3,
["bye"] = 4,
[200] = 5
}
What I mean is that when I use "in pairs" I'll get a different order everytime I execute my code ...
I'm searching for something like this:
function get_keys(tbl)
local rtable = {}
for k,v in pairs(tbl) do
table.insert(rtable, k)
end
return rtable
end
local keys_of_tbl = get_keys(tbl)
for i = 1, table.getn(keys_of_tbl) do
--Do something with: tbl[keys_of_tbl[i]]
end
But because the function "get_keys" is based on "in pairs" again, it won't work ...
In Lua, the order that pairs iterates through the keys is unspecified. However you can save the order in which items are added in an array-style table and use
ipairs
(which has a defined order for iterating keys in an array). To help with that you can create your own ordered table using metatables so that the key order will be maintained when new keys are added.EDIT (earlier code inserted multiple copies of the key on updates)
To do this you can use
__newindex
which we be called so long as the index is not added yet to the table. Theordered_add
method updates, deletes, or stores the key in the hidden tables_keys
and_values
. Note that__newindex
will always be called when we update the key too since we didn't store the value in the table but instead stored it in the "hidden" tables_keys
and_values
.Note however that we cannot use any key in this table, the key name
"_keys"
will overwrite our hidden table so the safer alternative is to use theordered_table.insert(t, key, value)
ordered_table.index(t, key)
andordered_table.remove(t, key)
methods.