Jump to content

User talk:Gechy/lua tutorial

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia
This is the current revision of this page, as edited by RexxS (talk | contribs) at 21:52, 15 January 2021 (if/else as an expression). The present address (URL) is a permanent link to this version.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

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)[reply]