User talk:Gechy/lua tutorial
Appearance
if/else as an expression
[edit]One of the commonest uses of logical and/or is to make a compact if ... then ... elseif ... end statement (make sure you write elseif, not else if).
Assigning x to one of a number of values a, b, c, ... y, z, depending on the value of a variable val can be done traditionally:
if val > v1 then
x = a
elseif val > v2 then
x = b
elseif val > v3 then
x = c
...
elseif val > v25 then
x = y
else
x = z
end
Optionally, it can be written:
x = (val > v1) and a
or (val > v2) and b
or (val > v3) and c
...
or (val > v25) and y
or z
Note that the latter is a single statement, but I've spread it out over several lines to emphasise the parallel between the two methods. --RexxS (talk) 21:52, 15 January 2021 (UTC)