Jump to content
  • Advertisement
Sign in to follow this  

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

This topic is 2097 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:


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;


[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

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:



n = lua_tointeger(l,1)

name = lua_tostring(l,2)




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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!