如何将全局值从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 side 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
推送到堆栈并将其传递到脚本中即可。 就像是:
// ... 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
访问该会话值。