Accessing Lua from C #
Assuming
You 've loaded your Lua assemblies (LIL files) into the global scope,
How do you access functions and variables in Lua from C #?
Lua global scope is defined inside the luastate global table (L. globals usually) and can be accessed like any luatable.
Luatable have a number of help overrides to make access fairly nice.
For example say you wanted to print some text via the Lua print
Function. First you have to retrieve the luafunction representing this
Call.
LuaFunction print = (LuaFunction) L.Globals["print"].O;
Then you have to push a string onto the Lua call stack but the are helpers for that and make the call
print.Call( new Object[]{ "Hello World" } );
You
Will probably notice this is similar but not quite the same, as how
Assembly was originally brought into Lua global state. Cos it is,
Compiler makes the Lua chunk into a function, that you then call
Execute the chunk. The loader just manually inserted things onto
Stack rather than using the overridden call
Now lets insert a C # function into the Lua global state, first we need to create a luafunction that wraps the C # function.
// prints hello world + the parameter passed in and return 5.0
public class SpecialHelloWorld : LuaFunction
{
public SpecialHelloWorld(LuaReference globals)
: base(globals)
{
}
public override int Execute(LuaState L)
{
int index = L.Stack.Base;
int top = L.Stack.Top - 1;
// retrieve the first parameter at index and turn it into a string
// add hello world and trace it
System.Diagnostics.Trace.Write( "Hello World" + L.Stack[index].ToString() );
L.Stack[top] = 5.0; // a return value
return 1; // number of return values (lua can have multiple return values)
}
}
Then create an instance of this function and insert it into the global table
L.Globals["Hello_World"] = new SpecialHelloWorld(L.Globals);
You can use similar code to insert variables, there are a number of casts and conversion functions to make this a bit nicer.
L.Globals["my_name"] = "DeanoC";
L.Globals["my_iq"] = -5.0f;
To access these in Lua it couldn't be any simplier
function PrintNameAndIQ()
print( "my name is ", my_name, " my iq is ", my_iq)
local var = Hello_World( "some text" )
if var == 5.0 then
print( "woot it returned the magic number 5.0" )
end
end