Lua function call without script execution

I embed Lua in a C / C ++ application. Is there a way to call a Lua function from C / C ++ without executing the whole script?

I tried to do this:

//call lua script from C/C++ program luaL_loadfile(L,"hello.lua"); //call lua function from C/C++ program lua_getglobal(L,"bar"); lua_call(L,0,0); 

But this gives me the following:

 PANIC: unprotected error in call to Lua API (attempt to call a nil value) 

I can call bar () when I do this:

 //call lua script from C/C++ program luaL_dofile(L,"hello.lua"); //this executes the script once, which I don't like //call lua function from C/C++ program lua_getglobal(L,"bar"); lua_call(L,0,0); 

But this gives me the following:

 hello stackoverflow!! 

I want this:

 stackoverflow! 

This is my lua script:

 print("hello"); function bar() print("stackoverflow!"); end 
+7
c ++ c lua
source share
3 answers

As just discussed in #lua on freenode, luaL_loadfile simply compiles the file into the called fragment, at that moment none of the code inside the file was started (including function definitions), as such, to get the definition of bar, to execute the piece, it should be called (which is what luaL_dofile does).

+13
source share

Found that a script must be executed to call a function.

+1
source share

One possible solution is / hack (and please remember that I currently cannot verify this) ...


Insert a fictitious "return"; line at the top of your LUA code.

  • Upload the file to a line (for example, when preparing luaL_loadstring() )
  • Now you just need to use printf_s("return;\r\n%s", [pointer to string holding actual LUA code] )
  • Now you can luaL_loadstring() concatenated string

The code will still be executed, but it must be disabled before it can achieve anything that does something (in your example print("hello"); the print line will become inaccessible). It should still update the list of all function prototypes, and now you can use lua_get() to refer to the functions.


NOTE. For those who don’t know "\ r \ n" , these are escape codes representing a new line in Windows, and MUST be these slashes ... IE: THIS \ r \ n NOT THIS / r / n

0
source share

All Articles