加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua变量范围

发布时间:2020-12-14 21:49:10 所属栏目:大数据 来源:网络整理
导读:我知道还有其他类似的主题,但找不到我的问题的直接答案. 假设你有一个如下功能: function aFunction() local aLuaTable = {} if (something) then aLuaTable = {} endend 对于if语句中的aLuaTable变量,它仍然是本地的吗?基本上我要问的是,如果我第一次将变
我知道还有其他类似的主题,但找不到我的问题的直接答案.

假设你有一个如下功能:

function aFunction()
  local aLuaTable = {}
  if (something) then
     aLuaTable = {}
  end
end

对于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"] = 20

x = 20       -- writes to the VM register associated with x
y = 30       -- translated to _ENV["y"] = 30

print(x)     -- reads from the VM register
print(y)     -- translated to print(_ENV["y"])

当地人有词汇范围.其他一切都在_ENV中.

x = 999

do -- 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 hiding
end

print(x) -- 999

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读