lua call function from a string with function name

Viewed 44476

Is it possible in lua to execute a function from a string representing its name?
i.e: I have the string x = "foo", is it possible to do x() ?

If yes what is the syntax ?

5 Answers

I frequently put a bunch of functions in a table:

functions = {
       f1 = function(arg) print("function one: "..arg) end,
       f2 = function(arg) print("function two: "..arg..arg) end,
       ...,
       fn = function(arg) print("function N: argh") end,
}

Then you can use a string as an table index and run your function like this

print(functions["f1"]("blabla"))
print(functions["f2"]("blabla"))

This is the result:

function one: blabla
function two: blablablabla

I find this to be cleaner than using loadstring(). If you don't want to create a special function table you can use _G['foo'].

Related