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

时间:2014-06-20 12:37:33

标签: lua

我有一个函数,我在其中声明了一个全局变量obs,在函数内部并赋予了一些值。如果我想在其他lua文件中访问它,则会出错:"尝试要将obs称为零值,我需要做些什么来才能访问它?

这是它的虚拟代码

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

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

2 个答案:

答案 0 :(得分:5)

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

a.lua

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

b.lua

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

x(); y();

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

你可能想要做这样的事情以获得更好的可移植性(哪个模块以这种方式定义哪个功能也更清晰):

a.lua

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

function get_obs()
    return obs_
end

return { x = x, obs = get_obs }

b.lua

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


a.x()
y()

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

a.lua

-- 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

b.lua

-- 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()

答案 1 :(得分:1)

请记住,其他程序中的一些Lua程序(Garry&#mod;魔兽世界,Vera,Domoticz)使用_ENV代替_G来限制其范围。所以全局变量必须是:

_ENV.variable = 1

而不是:

_G.variable = 1

发生这种情况的原因是因为开发人员想要限制标准的Lua库以避免用户访问方法,如:os.exit()。

要查看是否使用_ENV而不是_G,请将其打印出来,如果它返回的是表而不是nil,则最有可能使用它。您还可以使用以下代码段进行测试:

print(getfenv(1) == _G)
print(getfenv(1) == _ENV)

正在使用的那个是你正在使用的那个。