Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua library -- returning an array in lua from C

Tags:

c

lua

I'm not sure if the title correctly reflects my question.

I have a library implemented in C for lua provided to me by my employer. They have it reading a bunch of data out of a modbus device such that:

readFunc(Address, numReads) 

will start at Address and read numRead amount of registers. Currently this returns data in the following way:

A, B, C, D = readFunc(1234, 4)

However, we need to do 32+ reads at a time for some of our functions and I really don't want to have reply1, reply2... reply32+ listed in my code every time I do this. Ideally, I would like to do something like:

array_of_awesome_data = {}
array_of_awesome_data = readFunc(1234, 32)

where array_of_awesome_data[1] would correspond to A in the way we do it now. In the current C code I was given, each data is returned in a loop:

lua_pushinteger(L, retData);

How would I go about adjusting a C implemented lua library to allow the lua function to return an array?

Note: a loop of multiple reads is too inefficient on our device so we need to do 1 big read. I do not know enough of the details to justify why, but it is what I was told.

like image 436
Sambardo Avatar asked Aug 11 '11 19:08

Sambardo


1 Answers

In Lua, you can receive a list returned from a function using table.pack, e.g.:

array_of_awesome_data = table.pack(readFunc(1234, 32))

Or in C, if you want to return a table instead of a list of results, you need to first push a table onto the stack, and then push each item on the stack and add it to the table. It would have something like the following:

num_results=32; /* set this dynamically */
lua_createtable(L, num_results, 0);
for (i=0; i<num_results; i++) {
  lua_pushinteger(L, retData[i]);
  lua_rawseti (L, -2, i+1); /* In lua indices start at 1 */
}
like image 58
BMitch Avatar answered Sep 23 '22 13:09

BMitch