如何将全局值从C传递给LUA? [英] How to pass a global value from C to LUA?
问题描述
最近我尝试在我的C应用程序中嵌入LUA,现在我想要做的是我有一个值(Session_ID),我想从C函数传递给LUA脚本,以便LUA可以使用它脚本在C中调用一个函数。
在C中加载LUA脚本并运行它(使用lua_pcall)没有问题,我也没问题从LUA里面的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 side script.lua):
printStart
for i = 1,10 do
print(i,** session_id **)
end
printEnd
print 被我自己的函数覆盖,我想将 session_id 传递给它。
所以完整的场景是我在c函数中有 session_id ,我想将它传递给LUA脚本,稍后它将使用它来调用用C编写的打印函数。
有任何帮助:)?
session_id
放入堆栈,并在
// ...
result = lua_load(L,luaByteCodeReader,file,script, BT);
lua_pushinteger(L,session_id);
if(lua_pcall(L,1,0,0)!= 0)
// ...
让脚本像访问它一样:
本地session_id = ...
print 开始
i = 1,10
print(i,session_id)
结束
print结束
另一种方法,虽然不太吸引人,但是在lua的全球环境中添加 session_id
:
// ...
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)
//其余的代码
script.lua
现在可以通过 session_id
访问该会话值。
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.
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.
For example:
At C side (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).
At Lua side 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. 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.
Any help with that :)?
Just push session_id
onto the stack and pass it into the script when you pcall
it. 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:
// ...
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
.
这篇关于如何将全局值从C传递给LUA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!