This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
Programming in Lua | ||
Part I. The Language Chapter 3. Expressions |
print(4 and 5) --> 5 print(nil and 13) --> nil print(false and 13) --> false print(4 or 5) --> 4 print(false or 5) --> 5Both and and or use short-cut evaluation, that is, they evaluate their second operand only when necessary.
A useful Lua idiom is x = x or v
,
which is equivalent to
if not x then x = v endi.e., it sets
x
to a default value v
when
x
is not set
(provided that x
is not set to false).
Another useful idiom is (a and b) or c
(or simply a and b or c
,
because and has a higher precedence than or),
which is equivalent to the C expression
a ? b : cprovided that
b
is not false.
For instance, we can select the maximum of two numbers
x
and y
with a statement like
max = (x > y) and x or yWhen
x > y
, the first expression of the and is true,
so the and results in its second expression (x
)
(which is also true, because it is a number),
and then the or expression results in the value of
its first expression, x
.
When x > y
is false, the and expression is false
and so the or results in its second expression, y
.
The operator not always returns true or false:
print(not nil) --> true print(not false) --> true print(not 0) --> false print(not not nil) --> false
Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved. |