[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: how to call a local function by its name?
- From: Nagaev Boris <bnagaev@...>
- Date: Mon, 8 Jun 2015 19:12:51 +0000
Hello Dmitry
On Mon, Jun 8, 2015 at 6:56 PM, 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" }
Replace this line with
local fn = { func1, func, 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".
Normally a local variable can't be accessed by its name as a string.
The workaround is debug.getlocal [1]
[1] http://www.lua.org/pil/23.1.1.html
--
Best regards,
Boris Nagaev