Search code examples
c#luanlua

Can I create an NLua.LuaFunction without the name of the Lua function?


I am trying to make a method that evaluates a string and returns a LuaFunction object for the function contained in it. These strings will be input by a user so I can't know the names of the functions beforehand. Example string:

function doSomething()
    print('x')
end

I want the LuaFunction to point to doSomething.

I was able to use a regex to capture the name of the function and then use NLua.Lua.GetFunction but that didn't work with functions in functions.

Right now my code uses KeraLua.Lua.LoadString and returns a LuaFunction for the chunk created by LoadString. This sort of works but it means the LuaFunction can't take args.

This answer is similar to what I want, but I can't force the functions to be members of a table like it shows.


Solution

  • You have to use DoString rather than LoadString. LoadString does not execute the code it just compiles it to be run later, so it does not define the function in state. the function must be defined for GetFunction or indexing to work.

    If the input string is only a function define then you can do either of these:

    Lua state = new Lua();
    state.DoString((string)s); //define function in state by executing the input.
    
    LuaFunction f1 = state.GetFunction("doSomething");
    f1.Call("f1");
    
    LuaFunction f2 = (LuaFunction)state["doSomething"];
    f2.Call("f2");
    

    Example user input:

    function doSomething(s)
        print(s)
    end
    

    This solution does not cover local functions or functions which are stored in tables.