1. Variables and flow control
1. Variables and flow control
-- Two dashes start a one-line comment.
--[[
Adding two ['s and ]'s makes it a
multi-line comment.
--]]
----------------------------------------------------
-- 1. Variables and flow control.
----------------------------------------------------
-- In general, Global variables start with uppercase,
-- Local variables start with lowercase.
Num = 42 -- All numbers are doubles.
-- Don't freak out, 64-bit doubles have 52 bits for
-- storing exact in values; machine precision is
-- not a problem for ints that need < 52 bits.
S = 'walternate' -- Immutable strings like Python.
T = "double-quotes are also fine"
U = [[Double brackets
start and end
multi-line strings.]]
T = nil -- Undefines T; Lua has garbage collection.
-- Blocks are denoted with keywords like do/end:
while Num < 50 do
Num = Num + 1 -- No ++ or += type operators (Be careful).
end
-- If clauses:
-- "then" is a slave of "~if"
if Num > 40 then
print("over 40 'HELLO'")
-- Python == "elif" / Lua == "elseif-then"
elseif S ~= "walternate" then -- ~= is not equals.
-- Equality check is == like Python; ok for strs.
io.write("not over 40\n") -- Defaults to stdout.
else
-- Variables are global by default.
ThisIsGlobal = 5 -- CamelCase is common.
-- How to make a variable local:
local line = io.read() -- Reads next stdin line.
-- String concatenation uses the .. operator:
print("Winter is coming, " .. line)
end
-- Undefined variables return nil.
-- This is not an error:
Foo = anUnknownVariable -- Now Foo = nil.
ABoolValue = false
-- Only nil and false are falsy; 0 and '' are true!
if not ABoolValue then print("it was false") end
-- 'or' and 'and' are short-circuited.
-- This is similar to the a?b:c operator in C/js:
Ans = ABoolValue and 'yes' or 'no' --> 'no'
KarlSum = 0
for i = 1, 100 do -- The range includes both ends.
KarlSum = KarlSum + i
end
-- Use "100, 1, -1" as the range to count down:
FredSum = 0
for j = 100, 1, -1 do FredSum = FredSum + j end
-- In general, the range is begin, end[, step].
-- Another loop construct:
repeat
Num = Num - 1
until Num == 0
References