这里有一个代码示例如何使用 LuaInterface 中使用的 LuaDLL 类来重定向 lua 打印函数:
// See http://medek.wordpress.com/2009/02/03/wrapping-lua-errors-and-print-function/
static int LuaPrint(IntPtr L)
{
int nArgs = LuaDLL.lua_gettop(L);
LuaDLL.lua_getglobal(L, "tostring");
string ret = ""; //this is where we will dump the output
//make sure you start at 1 *NOT* 0
for(int i = 1; i <= nArgs; i++)
{
LuaDLL.lua_pushvalue(L, -1);
LuaDLL.lua_pushvalue(L, i);
LuaDLL.lua_call(L, 1, 1);
string s = LuaDLL.lua_tostring(L, -1);
if(s == null)
return LuaDLL.luaL_error(L, "\"tostring\" must return a string to \"print\"");
if(i > 1) ret += "\t";
ret += s;
LuaDLL.lua_pop(L, 1);
};
//Send it wherever
Console.Out.WriteLine(ret);
return 0;
}
C# 中 lua 的初始化如下所示:
IntPtr luaState = LuaDLL.luaL_newstate();
LuaDLL.luaL_openlibs(luaState);
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_setglobal(luaState, "luanet");
Lua l = new Lua(luaState.ToInt64());
LuaDLL.lua_register(luaState, "print", new LuaCSFunction(LuaPrint));