[英]How to pass a global value from C to LUA?
Recently I manged to embed LUA in my C application, what I'm trying to do now is thatI have a value (Session_ID) I want to pass from C function to a LUA script, so that it can be used by LUA script to Call a function back in C. 最近,我试图将LUA嵌入我的C应用程序中,现在我要做的是我有一个值(Session_ID),我想将其从C函数传递给LUA脚本,以便LUA脚本可以使用它来调用C中的函数
I have no problem loading LUA script in C and running it (using lua_pcall), and I have no problem as well to call the C function from inside LUA, my current problem is passing global variable back and forth. 我在用C加载LUA脚本并运行它(使用lua_pcall)时没有问题,从LUA内部调用C函数也没有问题,我当前的问题是来回传递全局变量。
For example: 例如:
At C side (test.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 )
Where file is the array containing the LUA script (script.lua). 其中file是包含LUA脚本(script.lua)的数组。
At Lua side script.lua): 在Lua一侧script.lua):
print "Start"
for i=1,10 do
print(i, **session_id**)
end
print "End"
"print" is overwritten by my own function, and I want to pas the session_id to it. 我自己的功能覆盖了“ print” ,我想将session_id粘贴到它上。 So the complete scenario is that I have the session_id in the c function, which I want to pass to the LUA script which will use it later to call the print function which is written in C.
因此,完整的方案是我在c函数中具有session_id ,我想将其传递给LUA脚本,该脚本稍后将使用它来调用用C编写的print函数。
Any help with that :)? 任何帮助:)?
Just push session_id
onto the stack and pass it into the script when you pcall
it. 只要按下
session_id
到堆栈中,并将其传递到脚本,当你pcall
它。 Something like: 就像是:
// ...
result = lua_load(L, luaByteCodeReader, file, "script", "bt");
lua_pushinteger(L, session_id);
if( lua_pcall(L, 1, 0, 0) != 0 )
// ...
Have your script access it like: 让您的脚本像这样访问它:
local session_id = ...
print "Start"
for i = 1, 10 do
print(i, session_id)
end
print "End"
Another alternative, though less appealing, is to add session_id
to lua's global environment: 另一个替代方法(虽然吸引力较小)是将
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
can now access that session value via session_id
. script.lua
现在可以通过session_id
访问该会话值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.