Lua Variables
Before using a variable, it needs to be declared in the code, which means creating the variable.
Before the compiler executes the code, it needs to know how to allocate storage for variable statements to store the values of the variables.
Lua variables have three types: global variables, local variables, and fields in tables.
Variables in Lua are global by default, even within blocks or functions, unless explicitly declared as local using local
.
The scope of a local variable extends from its declaration point to the end of the block it is in.
The default value for variables is nil
.
Example
-- test.lua script file
a = 5 -- global variable
local b = 5 -- local variable
function joke()
c = 5 -- global variable
local d = 6 -- local variable
end
joke()
print(c, d) --> 5 nil
do
local a = 6 -- local variable
b = 6 -- reassign local variable
print(a, b) --> 6 6
end
print(a, b) --> 5 6
Executing the above example outputs:
$ lua test.lua
5 nil
6 6
5 6
Assignment Statements
Assignment is the most basic method to change the value of a variable or a field in a table.
a = "hello" .. "world"
t.n = t.n + 1
a, b = 10, 2*x <--> a=10; b=2*x
Lua calculates all values on the right side before performing the assignment. This allows us to swap variable values:
x, y = y, x -- swap 'x' for 'y'
a[i], a[j] = a[j], a[i] -- swap 'a[i]' for 'a[j]'
When the number of variables does not match the number of values, Lua follows these strategies:
a. 变量个数 > 值的个数 按变量个数补足nil
b. 变量个数 < 值的个数 多余的值会被忽略
Example
a, b, c = 0, 1
print(a, b, c) --> 0 1 nil
a, b = a+1, b+1, b+2 -- value of b+2 is ignored
print(a, b) --> 1 2
a, b, c = 0
print(a, b, c) --> 0 nil nil
The last example above is a common error. Note: To assign multiple values to multiple variables, each variable must be assigned individually.
a, b, c = 0, 0, 0
print(a, b, c) --> 0 0 0
Multiple assignment is often used to swap variables or assign function return values to variables:
a, b = f()
f()
returns two values, the first is assigned to a
, the second to b
.
It is best to use local variables whenever possible, for two benefits:
- Avoid naming conflicts.
- Accessing local variables is faster than global variables.
Indexing
Indexing tables uses square brackets []
. Lua also provides the .
operator.
t[i]
t.i -- shorthand for when the index is a string
gettable_event(t, i) -- indexing is essentially a function call like this
Example
> site = {}
> site["key"] = "www.tutorialpro.org"
> print(site["key"])
www.tutorialpro.org
> print(site.key)
www.tutorialpro.org