在LUA中的函数内声明全局变量

Sim*_*aur 5 lua

我有一个函数,在其中声明了一个全局变量obs,并在函数中分配了一些值。如果我想在其他lua文件中访问它,则会出现错误:“试图调用obsnil值,我需要做什么?能够访问它吗?

这是它的伪代码

//A.lua
function X()
obs = splitText(lk,MAXLEN)
end

//B.lua
function Y()
for i=1, #obs do      //error at this line
end
end
Run Code Online (Sandbox Code Playgroud)

Mik*_*ran 8

有几种方法可以做到这一点。使用当前设置,您可以执行以下操作:

lu

function x()
    -- _G is the global table. this creates variable 'obs' attached to
    -- the global table with the value 'some text value'
    _G.obs = "some text value"
end
Run Code Online (Sandbox Code Playgroud)

lu

require "a"
function y()
     print(_G.obs); -- prints 'some text value' when invoked
end

x(); y();
Run Code Online (Sandbox Code Playgroud)

不过,在全局表中填充东西通常是一个糟糕的主意,因为其他任何地方的任何脚本都可能会覆盖值,使变量无效等。imo更好的方式是让a.lua在表中返回其功能。您可以将其捕获到需要它的文件中。这将允许您定义一个getter函数,以返回在其当前状态下直接附加到您的'a.lua'功能的'obs'变量。

您可能想要执行以下操作以提高可移植性(也更加清楚哪些模块以这种方式定义了哪些功能):

lu

local obs_
function x()
    obs_ = "some text value"
end

function get_obs()
    return obs_
end

return { x = x, obs = get_obs }
Run Code Online (Sandbox Code Playgroud)

lu

local a = require "a"
function y()
    print(a.obs())
end


a.x()
y()
Run Code Online (Sandbox Code Playgroud)

由于您提到您不能使用require,因此我假设您正在使用其他框架加载其他库/文件的其他框架中工作。在这种情况下,您可能只需要将所有内容填充到全局表中即可。也许是这样的:

lu

-- this will attach functions a_x and a_get_obs() to the global table
local obs_
function _G.a_x()
    obs_ = "some text value"
end

function _G.a_get_obs()
    return obs_
end
Run Code Online (Sandbox Code Playgroud)

lu

-- ignore this require, i'm assuming your framework has some other way loading
-- a.lua that i can't replicate
require "a"

function y()
    print(_G.a_get_obs())
end


_G.a_x()
y()
Run Code Online (Sandbox Code Playgroud)