Sign in to follow this  
Acharis

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

Recommended Posts

Acharis    5979

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
Acharis    5979

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
dlan_fr    555

[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

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