0基础lua学习(十九)C调用Lua----03C调用lua 函数和变量



下面的demo,主要演示 C如何访问 Lua中 函数、变量。

lua代码

function add(x,y)
      print("add") 
	  return x + y
end 

width = 100
height= 200
background = {r=0, g=0, b=1}



C代码

extern "C"  
{  

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

}  





lua_State* L;
int luaadd(int x, int y)
{
	int sum;
	/*调用函数名称*/
	lua_getglobal(L,"add");

	/*第一个参数*/
	lua_pushnumber(L, x);
	/*t第二个参数*/
	lua_pushnumber(L, y);

	/*调用函数两个参数一个返回值.*/
	lua_call(L, 2, 1);

	/*获取返回值*/
	sum = (int)lua_tonumber(L, -1);
	/*清空栈*/
	lua_pop(L,1);

	return sum;
}



//获取宽度和高度
int GetParam(int *width, int *height)
{	
	lua_getglobal(L, "width");
	lua_getglobal(L, "height");

	*width = (int)lua_tonumber(L, -2);
	*height = (int)lua_tonumber(L, -1);
	lua_pop(L,1);
	return 0;
}

#define MAX_COLOR 255
int getfield (const char *key)
{
	int result;
	lua_pushstring(L, key);
	lua_gettable(L, -2); /* get background[key] */
	//if (!lua_isnumber(L, -1))
	//	error(L, "invalid component in background color");
	result = (int)lua_tonumber(L, -1) * MAX_COLOR;
	lua_pop(L, 1); /* remove number */
	return result;
}


void GetTable()
{
	lua_getglobal(L, "background");


	int red = getfield("r");
	int green = getfield("g");
	int blue = getfield("b");
	printf("r:%d,g:%d,b:%d",red,green,blue);

}




int main()  
{  
	int sum;
	/*初始化lua*/
	L = lua_open();
	/*加载 Lua lib*/
	luaL_openlibs(L);
	/*打开hello.lua脚本*/
	luaL_dofile(L, "hello.lua");
	
	sum = luaadd(10, 15);
	printf("The sum is %d \n",sum);
	
	int width,height;
	GetParam(&width,&height);
	printf("%d,%d",width,height);
	GetTable();


	//关闭lua
	lua_close(L);
	return 0;  
}  


转载于:https://www.cnblogs.com/hiwoshixiaoyu/p/10034969.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值