
假设你有一个如下功能:
function aFunction() local aLuatable = {} if (something) then aLuatable = {} endend 对于if语句中的aLuatable变量,它仍然是本地的吗?基本上我要问的是,如果我第一次将变量定义为本地变量,然后我会一次又一次地使用它,它会在程序的其余部分保持在本地,这是如何工作的?
另外我读了Lua全局变量的这个定义:
Any variable not in a defined block is saID to be in the global scope.
Anything in the global scope is accessible by all inner scopes.
不是在一个定义的块中是什么意思?我的理解是,如果我在任何地方“声明”一个变量,它将永远是全局的,那是不正确的?
对不起,如果问题太简单,但来自Java和objective-c,对我来说,lua非常奇怪.
解决方法“Any variable not in a defined block is saID to be in the global scope.”
这是完全错误的,所以你的困惑是可以理解的.看起来你从用户维基得到了它.我刚刚用更正信息更新了页面:
任何未定义为本地的变量都是全局变量.
my understanding is that if I “declare” a variable anywhere it will always be global
如果您没有将其定义为本地,那么它将是全局的.但是,如果您随后创建具有相同名称的本地,则它将优先于全局(即,在尝试解析变量名时,Lua首先“看到”本地人).请参阅本文底部的示例.
If I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program’s life,how does this work exactly?
编译代码时,Lua会跟踪您定义的任何局部变量,并知道给定范围内可用的变量.每当您读/写一个变量时,如果该范围内有一个具有该名称的本地,则使用它.如果没有,则将读/写转换(在编译时)到表读/写(通过表_ENV).
local x = 10 -- stored in a VM register (a C array)y = 20 -- translated to _ENV["y"] = 20x = 20 -- writes to the VM register associated with xy = 30 -- translated to _ENV["y"] = 30print(x) -- reads from the VM registerprint(y) -- translated to print(_ENV["y"])
当地人有词汇范围.其他一切都在_ENV中.
x = 999do -- create a new scope local x = 2 print(x) -- uses the local x,so we print 2 x = 3 -- writing to the same local print(_ENV.x) -- explicitly reference the global x our local x is hIDingendprint(x) -- 999总结
以上是内存溢出为你收集整理的lua变量范围全部内容,希望文章能够帮你解决lua变量范围所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)