How to merge two tables overwriting the elements which are in both?
for k,v in pairs(second_table) do first_table[k] = v end
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”)
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
Your code is efficient but wrong. (Consider {[false]=0}.) The correct code is if next(myTable) == nil then — myTable is empty end For maximum efficiency you’ll want to bind next to a local variable, e.g., … local next = next … … if next(…) … (When next is local, the code finds primitive function next … Read more
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.
Lua is descended from Sol, a language designed for petroleum engineers with no formal training in computer programming. People not trained in computing think it is damned weird to start counting at zero. By adopting 1-based array and string indexing, the Lua designers avoided confounding the expectations of their first clients and sponsors. Although I … Read more