Jump to content
  • Advertisement
Sign in to follow this  
tamat

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.

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
Advertisement
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 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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!