开发者

Lua library -- returning an array in lua from C

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开发者_如何学C do 1 big read. I do not know enough of the details to justify why, but it is what I was told.


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 */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜