LUA BASICS for other language programmers

What do you need to know to start scripting in LUA?

1: 0 is true!

local v = 0
if v then
    print('YES! ZERO IS TRUE!')
    print('That is why many functions return "nil" (which is false)')
end

2: elseif != else if

if something then
    print(1)
else if somethingOther then
    print(2)
end

ERROR?! WHAT?! YES!
In LUA else if is one word elseif.
As there are no one-line ifs without end, you need to write:

if something then
    print(1)
elseif somethingOther then
    print(2)
end

or:

if something then<
    print(1)
else
    if somethingOther then
        print(2)
    end
end

Multi-line formatting is ignored, whole LUA program can be in 1 line!

3: Tables are indexed from 1!

Tables/arrays are indexed from 1, not 0!

local table = {1, 2, 3, 4, 5}
for k, v in pairs(table) do
    print(k .. ' = ' .. v)
end
print(table[0])

Result:

1 = 1
2 = 2
3 = 3
4 = 4
5 = 5
nil -- reading not assigned index returns magic "nil" from point 1

Leave a Reply

Your email address will not be published.