Jump to content
  • Advertisement
Sign in to follow this  
Acharis

[LUA][C++] getting parameters from a function

This topic is 1733 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 need a tiny little bit of LUA in my project (so I prefer to avoid relearning it). Can you tell me how to get parameters from a lua function to C++?

Last time I used LUA like 10 years ago and I forgot amost everything and the version changed many times since then :D

 

LUA file:

defineLocation(1,'World')
defineLocation(2,'City')

C++  code (problem is somewhere here)

int function(lua_State *l)
{
    int n=0;
    std::string name;

    int argc = lua_gettop(l);
    for(int i=0; i<argc; i++)
    {
        if(i==0) n=lua_tointeger(l, lua_gettop(l));
        if(i==1) name=lua_tostring(l, lua_gettop(l));

        lua_pop(l, 1);
    }

    printf("[notice] defineLocation(%d,%s)\n",n,name.c_str());

    return 0;
}

Output:

[notice] defineLocation(0,1)
[notice] defineLocation(0,2)

Desired output:

[notice] defineLocation(1,World)
[notice] defineLocation(2,City)

Share this post


Link to post
Share on other sites
Advertisement

OK, I managed to do it, I switched the order:

        if(i==1) n=lua_tointeger(l, lua_gettop(l));
        if(i==0) name=lua_tostring(l, lua_gettop(l));

But can someone explain me why? Are arguments from a functions inversed in lua? And generally tell if the code I wrote is written properly.

Share this post


Link to post
Share on other sites

[source]if(i==0) name=lua_tostring(l, lua_gettop(l));[/source]

 

Since lua_gettop give you the depth of the stack, even if i=0 in your case, lua_tostring will get the second argument pushed on the stack. after doing lua_pop, it will change the stack, hence give you the first argument.

 

you can get rid of your for loop and simply do:

 

[source]

n = lua_tointeger(l,1)

name = lua_tostring(l,2)

 

[/source]

 

lua_pop is unecessary, lua will take care of the stack in your case, it's only if you happen to push an additional value in your stack within your c++ function that you need to pop the value yourself.

 

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!