How to quickly initialise an associative table in Lua?
The correct way to write this is either local t = { foo = 1, bar = 2} Or, if the keys in your table are not legal identifiers: local t = { [“one key”] = 1, [“another key”] = 2}
The correct way to write this is either local t = { foo = 1, bar = 2} Or, if the keys in your table are not legal identifiers: local t = { [“one key”] = 1, [“another key”] = 2}
local keyset={} local n=0 for k,v in pairs(tab) do n=n+1 keyset[n]=k end Note that you cannot guarantee any order in keyset. If you want the keys in sorted order, then sort keyset with table.sort(keyset).
Overcomplicated answers much? Here is my implementation: function TableConcat(t1,t2) for i=1,#t2 do t1[#t1+1] = t2[i] end return t1 end
Table copy has many potential definitions. It depends on whether you want simple or deep copy, whether you want to copy, share or ignore metatables, etc. There is no single implementation that could satisfy everybody. One approach is to simply create a new table and duplicate all key/value pairs: function table.shallow_copy(t) local t2 = {} … Read more
You could use something like a set from Programming in Lua: function Set (list) local set = {} for _, l in ipairs(list) do set[l] = true end return set end Then you could put your list in the Set and test for membership: local items = Set { “apple”, “orange”, “pear”, “banana” } if … Read more
To iterate over all the key-value pairs in a table you can use pairs: for k, v in pairs(arr) do print(k, v[1], v[2], v[3]) end outputs: pears 2 p green apples 0 a red oranges 1 o orange Edit: Note that Lua doesn’t guarantee any iteration order for the associative part of the table. If … Read more
for k,v in pairs(second_table) do first_table[k] = v end
You are looking for the insert function, found in the table section of the main library. foo = {} table.insert(foo, “bar”) table.insert(foo, “baz”)
You can put the values as the table’s keys. For example: function addToSet(set, key) set[key] = true end function removeFromSet(set, key) set[key] = nil end function setContains(set, key) return set[key] ~= nil end There’s a more fully-featured example here.
No, setting the key’s value to nil is the accepted way of removing an item in the hashmap portion of a table. What you’re doing is standard. However, I’d recommend not overriding table.remove() – for the array portion of a table, the default table.remove() functionality includes renumbering the indices, which your override would not do. … Read more