6

I'm trying to pass a Lua table to my C program but I don´t know how to do it.

My Lua code:

local stages = {}
stages[1] = stage1
stages[2] = stage2
stages[3] = stage3

lstage.buildpollingtable(stages)

My C code:

static int lstage_build_polling_table (lua_State * L) {    
    luaL_checktype(L, 1, LUA_TTABLE);

    lua_getfield(L, 1, "stage1");
    lua_getfield(L, 1, "stage2");
    lua_getfield(L, 1, "stage3");

    stage_t s1 = lstage_tostage(L, -3);
    stage_t s2 = lstage_tostage(L, -2);
    stage_t s3 = lstage_tostage(L, -1);

    printf("%d\n",s1->priority);
    printf("%d\n",s2->priority);
    printf("%d\n",s3->priority);

    return 1;
}

What do I have to do to run all over the elements? This code generates an error like this:

bad argument #-3 to 'buildpollingtable' (lstage-Stage * expected, got table)

Can anyone explain what am I doing wrong?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
briba
  • 2,857
  • 2
  • 31
  • 59

1 Answers1

4

Your table does not have fields named stage1, etc., only fields 1, 2, 3. So try

lua_rawgeti(L,1,1);
lua_rawgeti(L,1,2);
lua_rawgeti(L,1,3);

instead of

lua_getfield(L, 1, "stage1");
lua_getfield(L, 1, "stage2");
lua_getfield(L, 1, "stage3");
lhf
  • 70,581
  • 9
  • 108
  • 149
  • However, the error message should be `..., got nil`. Perhaps using negative numbers is confusing `lstage_tostage`. – lhf Oct 29 '14 at 02:34
  • It returns this error: "warning: passing argument 3 of ‘lua_getfield’ makes pointer from integer without a cast [enabled by default]" =/ ...thanks for you help @lhf – briba Oct 30 '14 at 00:37
  • YEY! It´s working!!! Is there any way to know how many elements the table owns? because in this case I have 3 elements, but I can have 4,5,6... – briba Oct 30 '14 at 00:40
  • Do you know where can I find a sample of this method @lhf? – briba Oct 30 '14 at 00:44
  • @Crasher, I suggest you ask a separate question. – lhf Oct 30 '14 at 00:48