Accessing Lua from C#

Accessing Lua from C#

<!-- begin content -->

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 the assembly was originally brought into lua global state. Cos it is, the compiler makes the Lua Chunk into a function, that you then call to execute the chunk. The loader just manually inserted things onto the 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 function 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

你可能感兴趣的:(Access)