![](https://csdnimg.cn/release/download_crawler_static/10289416/bg14.jpg)
Getting Started
8
Variables have no predefined types; any variable can contain values of any type:
> type(a) --> nil ('a' is not initialized)
> a = 10
> type(a) --> number
> a = "a string!!"
> type(a) --> string
> a = nil
> type(a) --> nil
Usually, when we use a single variable for different types, the result is messy code. However, sometimes
the judicious use of this facility is helpful, for instance in the use of nil to differentiate a normal return
value from an abnormal condition.
We will discuss now the simple types nil and Boolean. In the following chapters, we will discuss in detail
the types number (Chapter 3, Numbers), string (Chapter 4, Strings), table (Chapter 5, Tables), and function
(Chapter 6, Functions). We will explain the thread type in Chapter 24, Coroutines, where we discuss
coroutines.
Nil
Nil is a type with a single value, nil, whose main property is to be different from any other value. Lua uses
nil as a kind of non-value, to represent the absence of a useful value. As we have seen, a global variable
has a nil value by default, before its first assignment, and we can assign nil to a global variable to delete it.
Booleans
The Boolean type has two values, @false{} and @true{}, which represent the traditional Boolean values.
However, Booleans do not hold a monopoly of condition values: in Lua, any value can represent a con-
dition. Conditional tests (e.g., conditions in control structures) consider both the Boolean false and nil
as false and anything else as true. In particular, Lua considers both zero and the empty string as true in
conditional tests.
Throughout this book, I will write “false” to mean any false value, that is, the Boolean false or nil. When
I mean specifically the Boolean value, I will write “false”. The same holds for “true” and “true”.
Lua supports a conventional set of logical operators: and, or, and not. Like control structures, all logical
operators consider both the Boolean false and nil as false, and anything else as true. The result of the and
operator is its first operand if that operand is false; otherwise, the result is its second operand. The result
of the or operator is its first operand if it is not false; otherwise, the result is its second operand:
> 4 and 5 --> 5
> nil and 13 --> nil
> false and 13 --> false
> 0 or 5 --> 0
> false or "hi" --> "hi"
> nil or false --> false
Both and and or use short-circuit evaluation, that is, they evaluate their second operand only when nec-
essary. Short-circuit evaluation ensures that expressions like (i ~= 0 and a/i > b) do not cause
run-time errors: Lua will not try to evaluate a / i when i is zero.
A useful Lua idiom is x = x or v, which is equivalent to
if not x then x = v end