Accessing Lua from C#

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 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
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值