Sign in to follow this  

calling a LUA function from C++

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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. :)

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this