2

最近我设法在我的 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 编写的打印函数。

有什么帮助:)?

4

1 回答 1

4

只需将其压入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-23T23:41:46.800 回答