Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Lua function without executing script

Tags:

c++

c

lua

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
like image 774
Person Avatar asked Feb 27 '10 02:02

Person


People also ask

How to call a Lua function?

The API protocol to call a function is simple: First, you push the function to be called; second, you push the arguments to the call; then you use lua_pcall to do the actual call; finally, you pop the results from the stack.

How to call Lua function from c++?

Calling Lua functions from C/C++ Push the arguments to the function on the lua stack, using the functions: lua_pushnumber(lua_state *L, float number) lua_pushstring(lua_state *L, char *str)

What is argument in Lua?

Arguments − An argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method.


2 Answers

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).

like image 147
Etan Reisner Avatar answered Oct 30 '22 02:10

Etan Reisner


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

like image 45
Person Avatar answered Oct 30 '22 02:10

Person