gpt4 book ai didi

variables - lua 变量作用域

转载 作者:行者123 更新时间:2023-12-04 22:23:19 25 4
gpt4 key购买 nike

我知道还有其他类似的主题,但找不到我的问题的直接答案。

假设您有一个函数,例如:

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

对于if语句里面的aLuaTable变量,还是local的吧?基本上我要问的是,如果我第一次将一个变量定义为本地变量,然后我一次又一次地使用它,它会在程序的其余部分保持本地状态,这究竟是如何工作的?

另外,我阅读了 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.



not in a defined block 是什么意思?,我的理解是,如果我在任何地方“声明”一个变量,它总是全局的,这不正确吗?。

对不起,如果问题太简单,但来自 Java 和 Objective-c,lua 对我来说很奇怪。

最佳答案

"Any variable not in a defined block is said to be in the global scope."



这完全是错误的,所以你的困惑是可以理解的。看起来你是从用户维基那里得到的。我刚刚用更正信息更新了页面:

任何未定义为 local 的变量是全局性的。

my understanding is that if I "declare" a variable anywhere it will always be global



如果您不将其定义为 local ,它将是全局性的。但是,如果您随后创建了 local具有相同的名称,它将优先于全局变量(即 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

关于variables - lua 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10654823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com