如何将一个全局值从 C 传递到 LUA?

最近我成功地在我的C应用程序中嵌入了LUA,现在我想要做的是,我有一个值(Session_ID),我想把它从C函数传递到LUA脚本中,以便它可以被LUA脚本用来回调C中的函数。

我在C中加载和运行LUA脚本(使用lua_pcall)没有问题,我也可以在LUA内部调用C函数,我的当前问题是在全局变量之间来回传递。

例如:

C侧(test.c):

session_id = 1;
luabc_sz = rlen;
result = lua_load(L, luaByteCodeReader, file, "script", "bt");
if( lua_pcall(L, 0, 0, 0) != 0 )

其中file是包含LUA脚本(script.lua)的数组。

LUA侧(script.lua):

print "Start"
for i=1,10 do
  print(i, **session_id**)
end
print "End"

“打印”被我自己的函数覆盖了,我想把session_id传递给它。因此,完整的场景是,我在c函数中有session_id,我想将其传递到LUA脚本中,以便以后可以用它来调用用C编写的打印函数。

有什么帮助吗?

点赞
用户234175
用户234175

只需将 session_id 推入栈中,并在 pcall 运行脚本时将其传入。类似于:

// ...
result = lua_load(L, luaByteCodeReader, file, "script", "bt");
lua_pushinteger(L, session_id);
if( lua_pcall(L, 1, 0, 0) != 0 )
// ...

你的脚本可以通过以下方式访问它:

local session_id = ...
print "Start"
for i = 1, 10 do
  print(i, session_id)
end
print "End"

另一种选择是将 session_id 添加到 Lua 的全局环境中,虽然这不太理想:

// ...
result = lua_load(L, luaByteCodeReader, file, "script", "bt");
lua_pushinteger(L, session_id);
lua_setglobal(L, "session_id");
if( lua_pcall(L, 0, 0, 0) != 0 )
// rest of your code

现在,script.lua 可以通过 session_id 访问该会话值。

2013-10-23 23:41:46