lua 不加前缀定义的为全局变量, 例如 :
i = 1 -- 这样定义的为全局变量.
定义本地变量使用local前缀, 例如 :
local i = 1 -- 定义一个本地变量.
本地变量的作用域比较诡异, 特别是在命令行中很"诡异", 需要理解这个chunk.
Unlike global variables, local variables have their scope limited to the blockwhere they are declared. A block is the body of a control structure, the body of afunction, or a chunk (the file or string where the variable is declared):
本地变量定义在一个函数体中, 那么作用域就在函数中.
如果定义在一个控制结构中, 那么就在这个控制结构中.
如果定义在一个文件中, 那么作用域就在这个文件中.
如果是使用命令行的话, 一条完整的命令就是一个chunk, 所以例如 :
> local i = 1> print(i)nil
因为上面那条local i = 1是一个chunk, 定义完就抛弃了.
所以下面打印的是全局变量i, 而不是本地变量i.
除非写在一个执行体中.
> do>> local i = 1>> print(i)>> end1
在命令行中一个chunk很好区分, >就是一个chunk , >>表示执行体未结束.
对于文件的话, 本地变量作用域在文件中, 所以以下文件可以打印出i=1
[root@db-172-16-3-150 ~]# vi lualocal i = 1print(i)[root@db-172-16-3-150 ~]# lua ./lua1
在控制结构中的例子 :
> if true then>> local x = 1>> print(x)>> end1> print(x) nil
> i = 0> while i < x dolocal x = i*2 -- this x is localprint(x)i = i+1end024681012141618>