calling a LUA function from C++

This topic is 4198 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi: Something weird is happening with my code, I can call my scripts and they work fine, I can call C function from my script and it works but if I want to call a specific function inside my script from C++ then it throws an error. This is my LUA script:
function sayhi()
io.write("Hello!\n")
end

io.write("Bye\n")

and this is my C++ code:
lua_getglobal(L, "sayhi");
status = lua_pcall(L, 0, LUA_MULTRET, 0);

I get the next error: -- attempt to call a nil value I'm using LUA 5.1. Does anybody knows why? Thanks in advance.

Share on other sites
Post all of your C++ code. I assume that you are loading the Lua script before trying to call the function but you did not post those lines so I cannot be sure.

Share on other sites
Well, its a little bit wrapped but more or less is this:

	L = lua_open();  // create state	luaL_openlibs(L);	status = luaL_loadfile(L, name);	lua_getglobal(L, function_name);	status = lua_pcall(L, 0, LUA_MULTRET, 0);	lua_close(L);

As I said I can do all the normal things, like calling the script as normal and it works perfect, so more or less everything is right. The problem is ONLY when I try to call an specific function inside the script, even if I call a external funcion registered inside LUA then it works, but not if the function is defined inside LUA.

Share on other sites
After the line
status = luaL_loadfile(L, name);
Lua has loaded the script from disk, compiled it and pushed it on top of the stack, but it has not been executed. Therefore, your function definition of sayhi() does not yet exist.

So, call
lua_pcall(L,0,0,0);
after the luaL_loadfile and you should be all right.

EDIT: The lua_pcall should actually do proper error handling:
if( lua_pcall(L,0,0,0) ) {   displayError( lua_tostring(L,-1) );   lua_pop(L,1);}

Share on other sites
Thanks a lot man. You are right. I thought that when it was compiled all the functions where put on the stack, now I see its when its executed.

I've been stucked in this error for two days.

Thanks again. :)

1. 1
Rutin
33
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 14
• Forum Statistics

• Total Topics
633330
• Total Posts
3011384
• Who's Online (See full list)

There are no registered users currently online

×