Jump to content
  • Advertisement
Sign in to follow this  
CoreWill

LUA Problem

This topic is 4811 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

I want to call a LUA function in my C program. Here is my code and the LUA version is 5.0.2:
int main(int argc, char *argv[])
{
    lua_State *pLuaState = lua_open();

    lua_baselibopen (pLuaState);
    lua_iolibopen (pLuaState);
    lua_strlibopen (pLuaState);
    lua_mathlibopen (pLuaState);
    lua_dblibopen (pLuaState);

    const char src[] = 
       "function Add( x, y ) r = x + y; return r; end";

    lua_dostring( pLuaState, src );

    lua_getglobal ( pLuaState, "Add" );
    lua_pushnumber ( pLuaState, 2 );
    lua_pushnumber ( pLuaState, 13 );
    lua_call ( pLuaState, 2, 1 );

    int iResult = ( int ) lua_tonumber ( pLuaState, 1 );
    lua_pop ( pLuaState, 1 );
    printf ( "Result: %d", iResult );

    lua_close ( pLuaState );

    return 0;
}


But the value of iResult is always 0, unless I remove the following code:
    lua_baselibopen (pLuaState);
    lua_iolibopen (pLuaState);
    lua_strlibopen (pLuaState);
    lua_mathlibopen (pLuaState);
    lua_dblibopen (pLuaState);


I'm new to LUA, so maybe I've made some mistake. Please tell me why I got the wrong result. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
Each of the libopens is leaving values on the stack for you. You can either clear them out by calling lua_settop(pLuaState, 0) after the libopens or you can get your result from index -1 (the top of the stack) instead of 1 (the bottom of the stack).

I didn't take the time to investgate what the return values are. You might want to look into that before you start ignoring them :)

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!