diff --git a/lua-basics.md b/lua-basics.md index 272028d..7402e60 100644 --- a/lua-basics.md +++ b/lua-basics.md @@ -21,16 +21,16 @@ Look for tutorials. Lua 5.1 to 5.4 all equally apply since the core language has - Use **==** to check for equality, **~=** to check for inequality (most other languages use **!=**, which does not exist in Lua) - The "table" is the only data structure that exists. They are arrays and hash maps in one. - Array indices start at 1 (not 0). This means an array A with N elements goes from A[1] til A[N]. -- A["key"] = 5 is the same as A.key = 5. -- A[0] can be used normally, but will not be picked up by the # operator or ipairs(). +- A.key = 5 is syntax sugar for A["key"] = 5. - You can use any value except nil as a table key. +- A[0], A[-42], etc. can be used normally, but will not be picked up by the # operator or ipairs(), because indices <= 0 end up in the hash part, not the array part of the table. - Table access: - Reading an index/key that doesn't exist returns nil - Writing an index/key that doesn't exist does an insert - `t[#t+1]` is one way to append a value to an array. - Alternatively, use `table.insert()`. - Write a *nil* value to erase a key -- Array length (# operator) is defined as (x - 1) for any integer i that satisfies `i >= 0 and A[i+1] == nil`. If multiple such i exist you may get one or the other (Lua does a binary search internally to find a suitable index i) +- Array length (# operator) is defined as an integer i that satisfies `i >= 0 and A[i] ~= nil and A[i+1] == nil`, ie. the index of some non-nil value followed by a nil. If multiple such i exist you may get one or the other (Lua does a binary search internally to find a suitable index i) - The ONLY values that are false-y in an if statement are false and nil. Anything else counts as true. Yes, 0, empty string, empty table all count as true-y. This is different in e.g. Python. - The global namespace can be accessed as the table _G (yes this is just a global symbol. Yes you can iterate over all globals and get a list of functions and constants that way.) - Any variable that is not marked 'local' is global. Variables not declared are assumed to be globals. That means if you want to call a function but typo the name, Lua will load the script without warnings. When the script is then run, Lua tries to fetch the typo'd symbol from _G, that fails so nil is returned; then it happily proceeds to call the result as a function, untilmately failing with "attempt to call a nil value".