Lua Basics

If Statements

This is the syntax of an if statement:

temperature = 98.6
if temperature == 98.6 then
    trace("temperature is 98.6") -- this statement is executed
end

The condition in the if statement is considered true if its value is anything other than false or nil. The value 0 is not equivalent to false. For example:

myvar = 0
if myvar then
    -- anything in here is executed, as 0 is treated as true
end

In Lua, the only values that are not evaluated as true are false and nil.

In the if statement, you can use elseif and else to define additional conditions to check for:

if temperature == 98.6 then
    trace("temperature is 98.6")
elseif temperature > 98.6 and temperature < 100 then
    trace("temperature is slightly above normal")
elseif temperature >= 100 then
    trace("patient has a fever")
else
    trace("temperature is below normal")
end

For more detailsee: control structures in the online reference manual, the Lua Tutorial wiki, or if then else in the online programming book.

Tagged:

Leave A Comment?