简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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