LUA BASICS for other language programmers

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

1: 0 is true!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
local v = 0
if v then
print('YES! ZERO IS TRUE!')
print('That is why many functions return "nil" (which is false)')
end
local v = 0 if v then print('YES! ZERO IS TRUE!') print('That is why many functions return "nil" (which is false)') end
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if something then
print(1)
else if somethingOther then
print(2)
end
if something then print(1) else if somethingOther then print(2) end
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if something then
print(1)
elseif somethingOther then
print(2)
end
if something then print(1) elseif somethingOther then print(2) end
if something then
    print(1)
elseif somethingOther then
    print(2)
end

or:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if something then<
print(1)
else
if somethingOther then
print(2)
end
end
if something then< print(1) else if somethingOther then print(2) end end
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!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
local table = {1, 2, 3, 4, 5}
for k, v in pairs(table) do
print(k .. ' = ' .. v)
end
print(table[0])
local table = {1, 2, 3, 4, 5} for k, v in pairs(table) do print(k .. ' = ' .. v) end print(table[0])
local table = {1, 2, 3, 4, 5}
for k, v in pairs(table) do
    print(k .. ' = ' .. v)
end
print(table[0])

Result:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1 = 1
2 = 2
3 = 3
4 = 4
5 = 5
nil -- reading not assigned index returns magic "nil" from point 1
1 = 1 2 = 2 3 = 3 4 = 4 5 = 5 nil -- reading not assigned index returns magic "nil" from point 1
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. Required fields are marked *