'Calling Lua function by string name

What I'm trying to do:

someTable={
    function Add(a,b)
        return a+b
    end

    function Mult(a,b)
        return a*b
    end

    function CallFunc(name,inputs)
 funcByName(table.unpack(inputs))
    end
}

And then I can call it from C#:

void Call(string name, params object[] inputs)

And the question is, how do I call a function by string name?

Also, CallFunc will be in metatable.

If there is any other way of solving the issue I'd also like to hear.

(Sorry for the formating but I'm writing from a phone for some reason)

Edit: T'was foolish of me to ask the question. What I was trying to to is to access a "member function" by its name. That is not really how lua works. So the answer is simply:

function CallFunc(self, name, ...)
    self[name](...)
end

And in C#:

void CallLuaFunc(LuaTable tb,string name,params object[] inputs){
    //call lua from c#
}

Thus the main c# program only needs to be compiled once since it can call any lua function by its name.

(BTW the library is XLua, a lua library for Unity3D to enable hotfix)



Solution 1:[1]

All global variables and functions are stored in the global table named _G, this makes you able to access a function by their string name. The following code prints "test" three times. Notice that the 3rd way uses a string to access it

function a()
  print("test")
end

a()
_G.a()
_G["a"]()

Solution 2:[2]

I would suggest to put the library in its own Lua file.

-- my-lib.lua

local Module = {}

function Module.Add(a,b)
  return a+b
end

function Module.Mult(a,b)
  return a*b
end

function Module.GenericCall(FunctionName,...)
  local Function = Module[FunctionName]
  if Function then
    return Function(...)
  end
end

return Module

Then the use of this library in another part of the Lua code is straight-forward:

local MyModule    = require("my-lib")
local GenericCall = MyModule.GenericCall

GenericCall("Add",  1, 2)
GenericCall("Mult", 1, 2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivo Beckers
Solution 2 Robert