簡體   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