2

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)

2
  • 1
    What library are you using? Commented May 24, 2022 at 7:48
  • Are you using MoonSharp? Commented May 24, 2022 at 13:25

2 Answers 2

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"]()
Sign up to request clarification or add additional context in comments.

2 Comments

Pedantically, they are stored in _ENV, which is usually the same as _G but you can also change it to a different one if you want.
@user253751 good to know, I wasn't aware of that
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.