2

How is it possible to call a function when running a lua script using NLua (A LuaInterface fork)?

For example, right now I have:

lua.LoadFile("C:\\test.lua")
lua.Call();

However, that just runs the script. Inside the script I have a custom function. I want to be able to run that function only. I tried:

lua.Call("functionTest")

But that didn't work. How can I do that?

My lua script is like so:

function functionTest()
   someMethod()
end

Or, if it's not possible - Is there a way to include different scripts inside one lua file? I want to be able to run the same file with different arguments for scripts, like:

script1 = {
    -- Code
}

script2 = {
    -- Code
}

Thanks.

user3865229
  • 125
  • 2
  • 9

1 Answers1

2

To run a function in Lua you need to first execute the script (the chunk) where the function is implemented.

For instance, if you have a chunk (x.lua)

 function MyFunction () 
      print ("MyFunction")
 end function

If you use NLua.Lua.LoadFile (which calls lua_load) the compiled code will be on the top of the stack, and you need to run to "declare" the function

The best way to do this is to use DoFile (), DoFile will load and run you chunk, and your function will be now "implemented".

To call your Lua function from C# all you gotta do is get the global value with your function name.

 lua.DoFile ("x.lua"); // Now MyFunction is declared
 LuaFunction myFunction = lua ["MyFunction"] as LuaFunction;
 myFunction.Call ();

Reference: NLuaBox Source code

Hope this can help you.

Vinicius Jarina
  • 797
  • 5
  • 16