C调用LUA函数返回的表

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄大刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值