Getting array value from index using Lua C Api

I have this array:

a = {{4,2,2,6}, {2,1,1,2}}

      

How can I get the index from this array into a C program?

For example:

a[1] -- {4,2,2,6}
a[1][2] -- 2

      

+3
c lua-table lua lua-api


source to share


2 answers


Try the following:

lua_getglobal(L,"a")
lua_rawgeti(L,-1,1)
lua_rawgeti(L,-1,2)

      



After that, the value a[1][2]

will be at the top of the stack. The stack will also contain a

and a[1]

, which you might want to post when you're done (they will remain on the stack if you want multiple values).

+3


source to share


You can use the method lua_gettable

. However, there are a few important notes:



  • Lua arrays start at index 1, not 0.
  • You need to push the index onto the lua stack via lua_pushinteger

    .
  • The key is "replaced" by the indexed item.
+6


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics