1

I'm really unsure about handling tables in the C API of Lua. The interface I'm currently developing requires me to read contents of a table given to my c function:

example.lua:

myVector2 = {["x"]=20, ["y"]=30}
setSomePosition(myVector2)

C function I register as "setSomePosition":

static int lSetSomePosition(lua_State *L)
{
    //number of arguments
    if(lua_gettop(L) != 1)
    {
        //error handling
        return 0;
    }
    //Need your help with the following:
    //extract tables values of indexes "x" and "y"

    return 0;
}

I know there are a couple of ways handling tables of which you sometimes need to know the indexes which I do. I'm just confused right now about this and the more I research the more I get confused. Probably because I don't really know how to describe what I'm after in proper terminology.

Would really appreciate some good commented example code of how you would fill in the gap in my c function :)

(If you've got an easy to understand guide to this topic don't mind commenting)

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
InDieTasten
  • 2,092
  • 1
  • 16
  • 24

1 Answers1

2
lua_getfield(L, 1, "x") //pushes a value of t["x"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack
lua_getfield(L, 1, "y") //pushes a value of t["y"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack
IS4
  • 11,945
  • 2
  • 47
  • 86
  • what does the positive one in the call of lua_getfield stand for? is it like when the c function call receives 2 tables I can increment it by one to push values from the second table on to the stack? – InDieTasten Nov 02 '14 at 17:06
  • 1
    @InDieTasten That's the stack index of the first argument (i.e. the table). – IS4 Nov 02 '14 at 17:10