繁体   English   中英

如何将全局值从C传递给LUA?

[英]How to pass a global value from C to LUA?

最近,我试图将LUA嵌入我的C应用程序中,现在我要做的是我有一个值(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"

我自己的功能覆盖了“ print” ,我想将session_id粘贴到它上。 因此,完整的方案是我在c函数中具有session_id ,我想将其传递给LUA脚本,该脚本稍后将使用它来调用用C编写的print函数。

任何帮助:)?

只要按下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访问该会话值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM