Lua 创建本地函数 table 不工作

Lua Create local function with table not working

嘿,我有 table 键代表函数名称,当我这样做时它有效

local example = {LocalFunction = true}
for fnName, _ in pairs(example) do
    _G[fnName] = function()
        print('This works')
    end     
end 
LocalFunction() -- output This Works

但是当我希望它是本地的时它不起作用有什么解决方案吗?

local example = {LocalFunction = true}

for fnName, _ in pairs(example) do
    local fnName = function()
        print('This works')
    end     
end 
LocalFunction() -- output nil value

提前致谢 Neo

正如lhf所说,你不能在运行时添加局部变量。您可以使用 debug.setlocal 修改它们,但需要在范围内定义它们。

适当的解决方法是包含函数的本地 table,例如:

local example = {LocalFunction = true}

local localFunctions = { }
for fnName, _ in pairs(example) do
    localFunctions[fnName] = function()
        print('This works')
    end     
end 
localFunctions.LocalFunction() -- output This Works

如果您由于某种原因不能使用table,您可以临时修改environment。 (http://lua-users.org/wiki/EnvironmentsTutorial)

-- create environment, use a metatable to use a protected copy of the old environment
local oldEnv = _ENV
local _ENV = setmetatable({}, {__index = _ENV})

local example = {LocalFunction = true}
for fnName, _ in pairs(example) do
    _ENV[fnName] = function()
        print('This works')
    end     
end 
LocalFunction() -- output This Works

-- restore environment, if required
_ENV = oldEnv

LocalFunction() -- no longer works