lua call function from a string with function name

后端 未结 5 2012
感动是毒
感动是毒 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:52

    To call a function in the global namespace (as mentioned by @THC4k) is easily done, and does not require loadstring().

    x='foo'
    _G[x]() -- calls foo from the global namespace
    

    You would need to use loadstring() (or walk each table) if the function in another table, such as if x='math.sqrt'.

    If loadstring() is used you would want to not only append parenthesis with ellipse (...) to allow for parameters, but also add return to the front.

    x='math.sqrt'
    print(assert(loadstring('return '..x..'(...)'))(25)) --> 5
    

    or walk the tables:

    function findfunction(x)
      assert(type(x) == "string")
      local f=_G
      for v in x:gmatch("[^%.]+") do
        if type(f) ~= "table" then
           return nil, "looking for '"..v.."' expected table, not "..type(f)
        end
        f=f[v]
      end
      if type(f) == "function" then
        return f
      else
        return nil, "expected function, not "..type(f)
      end
    end
    
    x='math.sqrt'
    print(assert(findfunction(x))(121)) -->11
    

提交回复
热议问题