Lua Create local function with table not working

Viewed 46

Hey I have table with keys thad represent the function names when i do this it works

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

But when I want it to be local it doesnt work is there any solution ?

local example = {LocalFunction = true}

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

Thanks in advance Neo

1 Answers

As lhf said, you can not add local variables at runtime. You can modify them using debug.setlocal, but they need to be defined within the scope.

A proper workaround would be a local table containing the functions, e.g.:

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

If you can not use a table for some reason, you could modify the environment in a temporary way. (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
Related