8

I am embedding Lua into a C/C++ application. Is there any way to call a Lua function from C/C++ without executing the entire script first?

I've tried doing 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 it gives me this:

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

I can only 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 it gives me this:

hello
stackoverflow!!

I am wanting this:

stackoverflow!

This is my lua script:

print("hello");

function bar()
 print("stackoverflow!");
end
1
  • 1
    Since you have to run the script to get the Lua VM to see it like Etan indicated you'll have to extract out function bar() to a different file and just run that file. Commented Jan 28, 2013 at 3:11

3 Answers 3

15

As was just discussed in #lua on freenode luaL_loadfile simply compiles the file into a callable chunk, at that point none of the code inside the file has run (which includes the function definitions), as such in order to get the definition of bar to execute the chunk must be called (which is what luaL_dofile does).

Sign up to request clarification or add additional context in comments.

2 Comments

I was the person who asked that on the chat :P
I figured you were, but figured I'd make the reference explicit anyway, just in case.
1

Found out that the script must be run to call the function.

Comments

0

One possible solution / hack (and please bear in mind that I'm currently unable to test this)...


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

  • Load your file into a string (like you would in preparation for using luaL_loadstring())
  • Now it should be a simple matter of using printf_s("return;\r\n%s", [pointer to string holding actual LUA code])
  • Now you can luaL_loadstring() the concatenated string

The code will still execute, but it should get cut off before it can actually reach anything that does something (in your print("hello"); example, the print line would become unreachable). It should still have updated the list of all the function prototypes and you should now be able to use lua_get() to reference the functions.


NOTE: For those who don't know "\r\n" are the escape codes representing a newline on the Windows OS, and it MUST be those slashes...   IE: THIS \r\n       NOT THIS /r/n

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.