What is the difference of pairs() vs. ipairs() in Lua?

pairs() and ipairs() are slightly different. pairs() returns key-value pairs and is mostly used for associative tables. key order is unspecified. ipairs() returns index-value pairs and is mostly used for numeric tables. Non numeric keys in an array are ignored, while the index order is deterministic (in numeric order). This is illustrated by the following … Read more

For Loop on Lua

Your problem is simple: names = {‘John’, ‘Joe’, ‘Steve’} for names = 1, 3 do print (names) end This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously … Read more

Define default values for function arguments

If you want named arguments and default values like PHP or Python, you can call your function with a table constructor: myfunction{a,b=3,c=2} (This is seen in many places in Lua, such as the advanced forms of LuaSocket’s protocol modules and constructors in IUPLua.) The function itself could have a signature like this: function myfunction(t) setmetatable(t,{__index={b=7, … Read more

Concatenation of strings in Lua

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

Can you make just part of a regex case-insensitive?

Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier. Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the … Read more

How to remove a lua table entry by its key?

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

subtle differences between JavaScript and Lua [closed]

Some more differences: Lua has native support for coroutines. UPDATE: JS now contains the yield keyword inside generators, giving it support for coroutines. Lua doesn’t convert between types for any comparison operators. In JS, only === and !== don’t type juggle. Lua has an exponentiation operator (^); JS doesn’t. JS uses different operators, including the … Read more