Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 retrieve an index from that array to a C program?

For example:

a[1] -- {4,2,2,6}
a[1][2] -- 2
like image 899
Victor Martins Avatar asked Jun 09 '26 04:06

Victor Martins


2 Answers

You can use the lua_gettable method. There are a few important notes, however:

  1. Lua arrays start at index 1, not 0.
  2. You'll need to push the index onto the lua stack via lua_pushinteger.
  3. The key is "replaced" with the indexed element.
like image 112
Drew McGowen Avatar answered Jun 11 '26 22:06

Drew McGowen


Try this:

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

After this, the value of a[1][2] will be on the top of the stack. The stack will also contain a and a[1], which you may want to pop when you're done (they're left on the stack in case you want to retrieve multiple values).

like image 22
lhf Avatar answered Jun 11 '26 21:06

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!