Skip to content

Declaration and scope of variables

Although Lua does not require to define types explicitly, it is still advisable to declare variables before using them. Local variables are declared with the local keyword either with or without an accompanying assignment. If a variable is not defined with local it is global, which means that it is visible (and over-writable) from other parts of the program. This can lead to unexpected results, especially when copy-pasting code or refactoring looping constructs. Also library functions might be overwritten which are then inaccessible to your Lua script.

It is recommended, therefore, to use local for every variable. In order to define variables that are accessible from all over a script, still use local and put the definitions on top of the file.

local height 
height = 10

local base_area = 30
local area = 1/3 * base_area * height

local i
for i=1,100 do
    local p = math.sqrt(i)
    cna.print(p)
end

cna.print(p) -- error.

The variables declared with local are only “visible” within the block where they were declared. In the former example, p is only visible within the for-loop, therefore the cna.print(p) invocation fails in the last line. In the next example, the declaration has been moved to an outer scope. Therefore it is also reachable by cna.print(p) in the last line:

local i
local p
for i=1,100 do
    p = math.sqrt(i)
    cna.print(p)
end
cna.print(p) -- 10