Lua Variables
Before a variable is used, it needs to be declared in the code, that is, the variable is created.
Before the compiler executes the code, it needs to know how to allocate storage for statement variables, in order to store the values of the variables.
Lua variables are of three types: global variables, local variables, and fields in a table.
Variables in Lua are all global, even in statement blocks or functions, unless explicitly declared as local using local.
The scope of a local variable is from the point of declaration to the end of the statement block it is in.
The default value of variables is nil.
Example
-- test.lua file script
a
=
5
-- Global variable
local
b
=
5
-- Local variable
function
joke
(
)
c
=
5
-- Global variable
local
d
=
6
-- Local variable
end
joke
(
)
(
c
,
d
)
--> 5 nil
do
local
a
=
6
-- Local variable
b
=
6
-- Reassign the local variable
(
a
,
b
)
;
--> 6 6
end
(
a
,
b
)
--> 5 6
The output of running the above example is:
$ lua test.lua
5 nil
6 6
5 6
Assignment Statements
Assignment is the most basic way to change the value of a variable and to change a table field.
a = "hello" .. "world"
t.n = t.n + 1
Lua can assign multiple variables simultaneously; the elements of the variable list and the value list are separated by commas, and the values on the right side of the assignment statement are assigned in order to the variables on the left.
a, b = 10, 2*x <--> a=10; b=2*x
When encountering an assignment statement, Lua first evaluates all the values on the right side and then performs the assignment, so we can swap the values of variables like this:
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 and the number of values do not match, Lua always adopts the following strategies based on the number of variables:
a. 变量个数 > 值的个数 按变量个数补足nil
b. 变量个数 < 值的个数 多余的值会被忽略
Example
a
,
b
,
c
=
0
,
1
(
a
,
b
,
c
)
--> 0 1 nil
a
,
b
=
a
1
,
b
1
,
b
2
-- value of b+2 is ignored
(
a
,
b
)
--> 1 2
a
,
b
,
c
=
0
(
a
,
b
,
c
)
--> 0 nil nil
The last example above is a common error situation. Note: when assigning to multiple variables, you must assign each variable in turn.
a, b, c = 0, 0, 0
print(a,b,c) --> 0 0 0
Multiple assignment is often used to swap variables, or to return the results of a function call to variables:
a, b = f()
f() returns two values; the first is assigned to a and the second to b.
You should use local variables as much as possible, for two reasons:
-
- Avoid naming conflicts.
-
- Accessing local variables is faster than accessing global variables.
Index
Use square brackets [] to index a table. Lua also provides the . operator.
t[i]
t.i -- 当索引为字符串类型时的一种简化写法
gettable_event(t,i) -- 采用索引访问本质上是一个类似这样的函数调用
Example
site
=
{
}
site
[
"key"
]
=
"www.runoob.com"
(
site
[
"key"
]
)
www
.
runoob
.
com
(
site
.
key
)
www
.
runoob
.
com