Lua variables
Before using a variable, it must be declared in the code, that is, the variable must be created.
Before the compiler executes the code, the compiler needs to know how to open a storage area for statement variables to store the value of the variable.
Lua variables have three types: global variables, local variables, and fields in tables.
Variables in Lua are all global variables, even in statement blocks or functions, unless they are explicitly declared as local variables using local.
The scope of local variables is from the declaration position to the end of the statement block.
The default value of variables is nil.
-- test.lua 文件脚本 a = 5 -- 全局变量 local b = 5 -- 局部变量 function joke() c = 5 -- 全局变量 local d = 6 -- 局部变量 end joke() print(c,d) --> 5 nil do local a = 6 -- 局部变量 b = 6 -- 全局变量 print(a,b); --> 6 6 end print(a,b) --> 5 6
The output result of executing the above example is:
$ lua test.lua 5 nil 6 6 5 6
Assignment statement
Assignment is the most basic method to change the value of a variable and change the table field.
a = "hello" .. "world" t.n = t.n + 1Lua can assign values to multiple variables at the same time. Each element of the variable list and value list is separated by commas. The value on the right side of the assignment statement will be assigned to the variable on the left in turn.
a, b = 10, 2*x <--> a=10; b=2*x
When encountering an assignment statement, Lua will first calculate all the values on the right and then perform the assignment operation, so we can exchange 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 are inconsistent , Lua will always adopt the following strategy based on the number of variables:
a. 变量个数 > 值的个数 按变量个数补足nil b. 变量个数 < 值的个数 多余的值会被忽略
For 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 situation. Note: If you want to assign values to multiple variables Each variable must be assigned a value in turn.
a, b, c = 0, 0, 0 print(a,b,c) --> 0 0 0
Multiple value assignment is often used to exchange variables, or return function calls to variables:
a, b = f()
f() returns two values, the first is assigned to a, and the second is assigned Give b.
You should use local variables as much as possible. There are two benefits:
1. Avoid naming conflicts.
2. Accessing local variables is faster than global variables.
Index
Use square brackets [] for table indexes. Lua also provides the . operation.
t[i] t.i -- 当索引为字符串类型时的一种简化写法 gettable_event(t,i) -- 采用索引访问本质上是一个类似这样的函数调用
For example:
> site = {} > site["key"] = "www.w3cschool.cc" > print(site["key"]) www.w3cschool.cc > print(site.key) www.w3cschool.cc