lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> it is work, but I'm interested in the ability to call a local function:

You can iterate over local variables to find the one with the name you need:

local function func1() print("local func1") end
local function func2() print("local func2") end

local fn = { "func1", "func2", "func3" }

local function name2value(target)
  for i = 1, math.huge do
    local name, value = debug.getlocal(2, i)
    if not name then return end
    if name == target then return value end
  end
end

for i = 1, 3 do
  local func_name = fn[i]
  pcall(name2value(func_name) or error("can't find local "..func_name))
end

Paul.

On Mon, Jun 8, 2015 at 11:56 AM, Dmitry V. Zaitsev <hhrhhr@gmail.com> wrote:
> example with table of functions:
>
> local T = {}
> function T.func1() print("func1") end
> function T.func2() print("func2") end
>
> local fn = { "func1", "func2", "func3" }
>
> for i = 1, 3 do
> local func_name = fn[i]
> pcall(T[func_name])
> end
>
> it is work, but I'm interested in the ability to call a local function:
>
> local function func1() print("local func1") end
> local function func2() print("local func2") end
>
> local fn = { "func1", "func2", "func3" }
>
> for i = 1, 3 do
> local func_name = fn[i]
> pcall(func_name) -- ???
> end
>
> of course, I get an error "attempt to call a string value".