lua call function from a string with function name

后端 未结 5 2003
感动是毒
感动是毒 2020-12-13 05:19

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() ?

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 05:46

    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'].

提交回复
热议问题