How do I append to a table in Lua
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 are looking for the insert function, found in the table section of the main library. foo = {} table.insert(foo, “bar”) table.insert(foo, “baz”)
As other answers have said, the string concatenation operator in Lua is two dots. Your simple example would be written like this: filename = “checkbook” filename = filename .. “.tmp” However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the … Read more
In lua 5.1, you can iterate of the characters of a string this in a couple of ways. The basic loop would be: for i = 1, #str do local c = str:sub(i,i) — do something with c end But it may be more efficient to use a pattern with string.gmatch() to get an iterator … Read more
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
Sure: print(“blah: ” .. (a and “blah” or “nahblah”))
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.
If the requirement is “quick and dirty” I’ve found this one useful. Because of the recursion it can print nested tables too. It doesn’t give the prettiest formatting in the output but for such a simple function it’s hard to beat for debugging. function dump(o) if type(o) == ‘table’ then local s=”{ ” for k,v … Read more
You already have the solution in the question — the only way is to iterate the whole table with pairs(..). function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end Also, notice that the “#” operator’s definition is a bit more complicated than that. Let … Read more
Use the tonumber function. As in a = tonumber(“10”).