博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lua变量作用域
阅读量:6693 次
发布时间:2019-06-25

本文共 1438 字,大约阅读时间需要 4 分钟。

3.5 – Visibility Rules

Lua is a lexically scoped language. The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration. Consider the following example:

x = 10                -- global variable     do                    -- new block       local x = x         -- new 'x', with value 10       print(x)            --> 10       x = x+1       do                  -- another block         local x = x+1     -- another 'x'         print(x)          --> 12       end       print(x)            --> 11     end     print(x)              --> 10  (the global one)

Notice that, in a declaration like local x = x, the new x being declared is not in scope yet, and so the second x refers to the outside variable.

Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an upvalue, or external local variable, inside the inner function.

Notice that each execution of a local statement defines new local variables. Consider the following example:

a = {}     local x = 20     for i=1,10 do       local y = 0       a[i] = function () y=y+1; return x+y end     end

The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different y variable, while all of them share the 

转载地址:http://qncoo.baihongyu.com/

你可能感兴趣的文章
第 四 十 天:关 于 正 则 的 一 些 小 用 法
查看>>
编程 -- awk
查看>>
2012 #3 Arcane Numbers
查看>>
python 列表模拟堆栰
查看>>
Linux-Centos5.3中文乱码问题解决
查看>>
linux分区学习[ CentOS ]
查看>>
aaa认证
查看>>
adb_安装软件
查看>>
廖雪峰官网学习js 字符串
查看>>
phpcms 如何获取文章
查看>>
C# 如何防止重放攻击(转载)
查看>>
C#匿名类型
查看>>
ActiveMQ
查看>>
Nginx服务器部署 负载均衡 反向代理
查看>>
C++学习笔记:指向函数的指针
查看>>
Child Action
查看>>
# 2017-2018-1 20155319 实验五 《通讯协议设计》
查看>>
通用后台管理系统(1)-数据库设计
查看>>
做自适应网页
查看>>
ACM的奇计淫巧_bitset优化
查看>>