Lua"要求"全球"本地"?

Bri*_*ian 6 lua scope module function

显然我有些混淆,但我想通过在"main.lua"中使用这样的东西:

local module = require("module")
local var = "I should be global?"
printthis()
Run Code Online (Sandbox Code Playgroud)

与module.lua包含类似的东西:

function printthis()
    print(var)
end
Run Code Online (Sandbox Code Playgroud)

这样printthis(var)可以正常工作,因为现在module.lua代码 main.lua 里面,不是吗?相反,printthis不知道是什么var.我认为在可能的情况下在Lua变量上使用"local"是一个好习惯,但在这种情况下,我是否必须使用varglobal或者有没有办法让module.lua的printthis()函数var正确读取?

Pup*_*ppy 23

不,这根本不是它的运作方式.

Lua解释器提供了一个全局表,通常称为_G,除非你做了一些淫乱的事情.

function printthis()
    print(var)
end
Run Code Online (Sandbox Code Playgroud)

实际上,这转化为

_G.printthis = function()
    _G.print(_G.var);
end
Run Code Online (Sandbox Code Playgroud)

你的代码在main中等于

local module = _G.require("module")
local var = "I should be global?"
_G.printthis()
Run Code Online (Sandbox Code Playgroud)

但是当你打电话printthis- 确定在哪里_G.var?无处.所以变量是nil,就像对该表没有任何内容的所有其他访问一样.

这可能是不方便,但它是一个从长远来看更好的主意来传递参数,而不是设置全局变量来代替.一旦你改变了程序的任何内容,就完全不可能做出任何改变,因为逻辑没有结构,你不知道在没有阅读每一行代码并立即理解它的情况下会发生什么.另外,你只能在一个地方使用每个键,因为它是一个全局表 - 所以我当然希望没有其他人想要使用"var"作为变量名,你不介意你的代码默默地失败,因为你有一个全局名字不对.


Jas*_*ijn 5

另外两个答案掩盖了一个重要的事情:词汇范围。

粗略地说,这意味着该代码可以访问在定义代码的地方定义的局部变量。这可能听起来很模糊,所以我举个例子:

local cheese = 'sandwich'
print(cheese) -- prints sandwich
do -- this begins an anonymous block
    local cheese = 22
    print(cheese) -- prints 22
end
print(cheese) -- prints sandwich
Run Code Online (Sandbox Code Playgroud)

所以我们这里有两个不同的变量:外部变量被内部变量“遮蔽”。

现在,进入功能:

do
    local hotdog = 'hot'
    function nonsense()
        print(hotdog)
    end
end
print(hotdog) -- prints nil, since there is no variable called hotdog here
nonsense() -- prints hot
Run Code Online (Sandbox Code Playgroud)

函数可以从定义它们的地方看到局部变量,而不是从它们被调用的地方。一旦你掌握了它,这是非常重要和非常有用的。