Overview of Lua language concepts

A quick overview of basic Lua language concepts is shown below.

Review chapters 1-5 of the Lua programming guide for more details.

Comments
--A comment
--[[ A
comment block
]]


Variables
local var1 -- Declaring a variable
local var2; -- Semicolon to end a statement (chunk) is optional
local var3 = nil -- nil is the default value for all uninitialized variables - similar to null in other languages
local VaR4 = "AbC" -- variables and strings are case-sensitive
local var5 = {} -- Declaring an array (a.k.a table)


Reserved names
and       break     do        else      elseif
end       false     for       function  if
in        local     nil       not       or
repeat    return    then      true      until
while


Variable types
local string = "Hello world"
local number = 10
local number2 = 10.4
local boolean = true
local function = type()


Escaping characters in strings
local string = "one line\nnext line\n\"in quotes\", 'in quotes'"


Tables - similar to arrays in other languages
local a = {} -- create a table
local a = {1,2,3} -- accessed as a[1]=1, a[2]=2, a[3]=3
local a = {one=1,two=2,three=3} -- accessed as a["one"]=1, a["two"]=2, a["three"]=3 or a.one=1, a.two=2, a.three=3
-- items are placed starting at [1] position when declaring like this
local a = {"one","two","three"} -- accessed as a[1]="one", a[2]="two", a[3]="three"
-- replacing array items
a[1] = "four"
a["x"] = "string"
a["y"] = 5


Operator precedence
^ (exponential)
not  - (unary operator)
*   /
+   -
.. (concatenation)
<   >   <=  >=  ~=  == (relational operators)
and (boolean operator)
or (boolean operator)


Parentheses control precedence
(a+i) < ((b/2)+1)


Concatenation
local b = "Hello ".."World"
local b = 0 .. 1 -- spacing required for numbers


Multiple assignments
a,b = 1,2
a,b = f() -- functions can return multiple results


If/then/else
if a<0 then a = 0 end
if a<b then return a else return b end


While loop
local i = 1
while a[i] do
  print(a[i])
  i = i + 1
end


For loop
for i=1,f(x) do dw.log.exception("INFO",i) end
for i=10,1,-1 do dw.log.exception("INFO",i) end
-- log all values of array 'a'
for i,v in ipairs(a) do dw.log.exception("INFO",v) end