redis lua local 作用域

来源:互联网 发布:java script没有提示 编辑:程序博客网 时间:2024/06/07 01:09
lua 不加前缀定义的为全局变量, 例如 : 
i = 1   -- 这样定义的为全局变量.
定义本地变量使用local前缀, 例如 : 
local i = 1 -- 定义一个本地变量.
本地变量的作用域比较诡异, 特别是在命令行中很"诡异", 需要理解这个chunk.

Unlike global variables, local variables have their scope limited to the block
where they are declared. A block is the body of a control structure, the body of a
function, 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)
>> end
1

在命令行中一个chunk很好区分, >就是一个chunk , >>表示执行体未结束.
对于文件的话, 本地变量作用域在文件中, 所以以下文件可以打印出i=1

[root@db-172-16-3-150 ~]# vi lua
local i = 1
print(i)
[root@db-172-16-3-150 ~]# lua ./lua
1

在控制结构中的例子 : 

> if true then
>> local x = 1
>> print(x)
>> end
1
> print(x)nil

> i = 0
> while i < x do
local x = i*2 -- this x is local
print(x)
i = i+1
end
0
2
4
6
8
10
12
14
16
18
> 
0 0
原创粉丝点击