Skip to reading
Lua Scripting

Values, variables and constants

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page

LESSON 03

Separate a number the player typed from the text that represents it.

Code example
local Script = {}
Code example
function Script.run(context)
    local MAX_TURNS <const> = 3
    local typed = "02"
    local turns = tonumber(typed)
    local allowed = turns ~= nil and turns <= MAX_TURNS
    local missing = nil
    return { raw = typed, turns = turns, allowed = allowed,
             missingType = type(missing) }
end
Code example
return Script

The result contains the string 02, the number 2, true and the type name nil. tonumber returns nil for

a word such as bell. Short-circuit evaluation of and protects the numeric comparison. Use tostring

for display and type to inspect a Lua value.

A local lives within its enclosing block. A declaration outside the module functions is shared by

those functions for the lifetime of that instance. An assignment to an undeclared name writes into

the Lua environment. Use local for temporary values and a PCA variable for progress that other

records must see.

The Lua 5.4 <const> attribute prevents reassignment. A constant table can still have its fields

changed. Only nil and false count as false in a conditional. The number 0 and an empty string both

count as true.

Page 21 of 133Permalink
Go to page