Skip to content

Program flow: control structures & loops

Lua features the typical set of looping and if, then, elseif and else constructs of typical extension and programming languages. Only the most important aspects will be outlined here.

Conditional Execution

if CONDITION then
    IF_BRANCH
elseif OTHER_CONDITION then
    ELSEIF_BRANCH
else
    ELSE_BRANCH
end

Condition is interpreted like boolean values, i.e. values that are not nil/false are considered to be true and lead to the IF_BRANCH being executed. Otherwise, OTHER_CONDITION is evaluated and depending on the evaluation result, either ELSEIF_BRANCH or ELSE_BRANCH are executed.

if 0 then 
    cna.print("A") 
else 
    cna.print("B"); 
end
-- result: "A"

if 3 > 10 or nil and false then 
    cna.print("C") 
else 
    cna.print("D"); 
end
-- result: "D"

An example from CadnaA-Lua might be as follows: Depending on the value of the LP1 attribute, a memo text variable will be written to:

for ip in cna.tables.imm:all() do
if ip.LP1 > 80 then
    ip.memo_var.CATEGORY = 1
elseif ip.LP1 > 65 then
    ip.memo_var.CATEGORY = 2
else
    ip.memo_var.CATEGORY = 3
end
cna.print(ip.BEZ.. "): CAT " ..ip.memo_var.CATEGORY)
end

Loops

Several looping constructs are available in Lua. repeat ... until CONDITION executes statements until the CONDITION evaluates to true. while CONDITION do ... end evaluates ... as long as the condition CONDITION evaluates to true. The most important looping construct for CadnaA-Lua, however, is the for do-Loop which comes in two varieties. The simple for loop is just counting from a value FROM, to a value TO by adding STEP to the value at each step.

local i
for i = FROM,TO,STEP do
    ....
end

The other looping construct iterates over data structures. This loop is heavily used by CadnaA-Lua extensions to apply operations on a set of CadnaA objects. Please note that the variable element is being declared with local, this is good practice and prevents mistakes.

local element
for element in list do
    ....
end

Functions

Functions can be defined in Lua directly. Typically, functions in CadnaA-Lua should also be declared using local:

local function squaring(x)
    return x * x
end

Now, the function can be invoked with

squaring(4) -- result: 16

A special kind of functions are so called methods. Methods functions that are associated with Lua tables. They are invoked with a colon: object:method(x1, x2, x3, ...). The fundamental property of methods is, that they are always dependent on the left-hand-side object. The colon notation can be expanded to the more complicated invocation of object.method(object, x1, x2, x3, ...).