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)
CodePudding user response:
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"]()
CodePudding user response:
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)