C语言调用LUA的程序,LUA程序返回表,C获取表格的内容。
例子如下:
C语言端:
int lua_collection_data(int if_id, char *ipaddr, int ipport, int devaddr){
float res;
int k;
double v;
const char *c;
lua_getglobal(L,"collection_data");
lua_pushnumber(L, if_id);
lua_pushstring(L, ipaddr);
lua_pushnumber(L, ipport);
lua_pushnumber(L, devaddr);
lua_call(L, 4, 1); //输入4个参数,返回1个参数(table)
lua_pushnil(L);
while(lua_next(L, -2)){
k = lua_tonumber(L, -2);
if(k==3) //表的索引3为字符串,其它为浮点点数
c = lua_tostring(L, -1);
else
v = (double)lua_tonumber(L, -1);
if(k==3)
printf("k=%d,c=%s\n", k, c); //打印测试
else
printf("k=%d,v=%f\n", k, v);
lua_pop(L,1);
}
return res;
}
LUA语言端:
function collection_data(if_id, ipaddr, port, devaddr)
print("if_id:", if_id);
print("ipaddr:", ipaddr);
print("ip port:", port);
print("dev addr", devaddr);
cmd = {devaddr, 0x04, 0x00, 0x00, 0x00, 0x02};
crc1, crc2 = dev_lib.calc_chksum(cmd, 6);
cmd[7] = crc1;
cmd[8] = crc2;
dev_lib.write_data(if_id, cmd, 8);
--以下是测试用的
spots[1] = 12.45
spots[2] = 32
spots[3] = "TEST MESSAGE"
--return 10,12,13;
return spots --返回表格
end
测试结果:
k=1,v=12.450000
k=2,v=32.000000
k=3,c=TEST MESSAGE