Accessing C# from Lua

So you can create special LuaFunction and insert them into the lua state, but what would be really nice is if you could just access all the normal C#/CLR types in Lua... with load_assembly and import_type you can.

Lets say you've added a class like this to your application which you want to expose to Lua

 
namespace LuaTest
{
    public class ClrTestType
    {
        public ClrTestType()
        {
            System.Diagnostics.Trace.Write("ClrTestType.ctor");
        }
        public void TestPrint(String txt)
        {
            System.Diagnostics.Trace.Write(txt);
        }
        public static double FiftyTwo = 52.0;
    }
}
 

The first thing you need is the name of the assembly its in, if its in you main exe it will be the name on disk without the .exe. Otherwise its the name of the assembly you want to use. Xnua keeps a cache of loaded assemblies, so you only have to do it once per assembly. Also if you have different names for you PC and XBOX360 main exes you will need that reflected, to make this easier there is _XBOX360 boolean in Lua that you can test. For example in the LuaTest sample this works

 
if _XBOX360 == true then
	load_assembly( "LuaTest" )
else
	load_assembly( "LuaTestPC" )
end
 

With the assembly loaded you can now import the type you want like so

 
ClrTestType = import_type( "LuaTest.ClrTestType" )
 

To access static member you just access the returned type like any lua table, to create an instance of that type use the () operator on the returned type. And to call member functions or variable of the instance use the instance:function syntax.

 
	print( ClrTestType.FiftyTwo )
	local testobj = ClrTestType()
	testobj:TestPrint( "woot CLR consumer hookup" )
 

Thats it really, you can now access class defined in C# without out any special code. Its worth noting that this is slower than exposing things by overriding LuaFunction because the interface code has to marshal types and look up function via reflection so its done at runtime.
Note at this moment, you CAN'T dynamically override a C# function with a Lua function via syntax like

 
--This will FAIL when you try and call it 
testobj:TestPrint = function() print("Override") end
--This will FAIL when you try and call it 
 

While its perfectly legal in lua to do this, as this moment that level of dynamic class manipulation isn't supported in base CLR types.


Posted on Tue, 2007-03-06 20:48 by deano
» login or register to post comments