Accessing Lua from C#

來源:互聯網
上載者:User
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
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.