[英]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.我在 C 中为我的雇主提供给我的 lua 实现了一个库。 They have it reading a bunch of data out of a modbus device such that:
他们让它从 modbus 设备中读取一堆数据,例如:
readFunc(Address, numReads)
will start at Address and read numRead amount of registers.将从 Address 开始并读取 numRead 数量的寄存器。 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.但是,对于我们的某些功能,我们需要一次读取 32 次以上,我真的不希望每次执行此操作时都会在我的代码中列出 reply1、reply2...reply32+。 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.其中 array_of_awesome_data[1] 将按照我们现在的方式对应于 A。 In the current C code I was given, each data is returned in a loop:
在我给出的当前 C 代码中,每个数据循环返回:
lua_pushinteger(L, retData);
How would I go about adjusting a C implemented lua library to allow the lua function to return an array? 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.注意:多次读取的循环在我们的设备上效率太低,因此我们需要进行 1 次大读取。 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
, eg:在 Lua 中,您可以使用
table.pack
接收从 function 返回的列表,例如:
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.或者在 C 中,如果要返回一个表格而不是结果列表,则需要先将一个表格压入堆栈,然后将堆栈上的每一项压入并添加到表格中。 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 */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.