Lua与C/C++的交互5:C/C++调用Lua函数

我想在Lua文件中定义一个Lua函数,然后用C/C++进行调用。调用函数的API协议其实非常简单。首先,将需要调用的函数压入栈中,并依次压入函数的参数。然后,通过lua_pcall进行实际的调用。最后,将调用结果从栈中弹出。以下是完整源代码:

#include "stdafx.h"
#include "stdio.h"
extern "C"
{
	#include "lua.h"
	#include "lualib.h"
	#include "lauxlib.h"
};

#pragma comment(lib,"lua5.1.lib")

//依次打印stack中元素(从栈底 -> 栈顶)
void stackDump(lua_State *L)
{
	int i;
	int top = lua_gettop(L);
	printf("the size of stack is:%d\n",top);
	for ( i = 1;i <= top;i++ )
	{
		int type = lua_type(L, i);
		switch(type)
		{
		case LUA_TSTRING:
			{
				printf("%s",lua_tostring(L, i));
				break;
			}

		case LUA_TBOOLEAN:
			{
				printf(lua_toboolean(L, i)?"true":"false");
				break;
			}
		case LUA_TNUMBER:
			{
				printf("%g",lua_tonumber(L, i));
				break;
			}
		case LUA_TTABLE:
			{
				printf("this is a table!");
				break;
			}
		default:
			{
				printf("%s",lua_typename(L ,i));
				break;
			}
		}
		printf(" ");
	}
	printf("\n");
}

//调用Lua中的函数fire
double fire(lua_State *L, double x, double y)
{
	double res;
	/*压入函数跟参数*/
	lua_getglobal(L, "fire");//待调用的Lua函数
	lua_pushnumber(L, x);	//压入第一个参数
	lua_pushnumber(L, y);	//压入第二个参数

	stackDump(L);
	/*完成调用(2个参数,一个返回结果)*/
	if ( lua_pcall(L, 2, 1, 0) != 0 )
		printf("run function 'f' error:%s",lua_tostring(L, -1) );

	stackDump(L);
	/*检索结果*/
	if ( !lua_isnumber(L, -1) )
		printf("function 'fire' must return a number");

	res = lua_tonumber(L, -1);
	lua_pop(L, 1);//弹出结果
	stackDump(L);
	return res;

}

//打开Lua文件并获取函数
void getLuaFunction(lua_State *L, const char *fname)
{
	if ( luaL_loadfile(L, fname) || lua_pcall(L, 0, 0 ,0) )
		printf("error,can't run config file:%s:",lua_tostring(L, -1));

	double result = fire(L, 2.3, 2.2);
	printf("the result is %f:",result);
}

int _tmain(int argc, _TCHAR* argv[])
{
	lua_State *L;
	L = luaL_newstate();
	luaL_openlibs(L);	
	getLuaFunction(L, "getLuaFunction.lua");
	return 0;
}

打印结果如下:

the size of stack is:3
boolean 2.3 2.2
the size of stack is:1
4.5
the size of stack is:0

the result is 4.500000:

其中Lua文件内容如下:

function fire(x, y)
	return x + y
end

详细解释下lua_pcall(lua_State *L, int nargs, int nresults, int errfunc): nargs是传给待调用函数的参数个数,nresults是期望的返回结果数量,errfunc是一个错误处理函数的索引。在压入结果前,lua_pcall会先删除栈中的函数及其参数。如果函数返回多个结果,那么第一个最先压入,依此类推。如果在lua_pcall运行的过程中有任何错误,它会返回一个非零值,同时弹出栈中函数及其参数,最后往栈中压入一条错误信息。然而,在压入错误消息前,如果存在一个错误处理函数,lua_pcall会先调用它。errfunc为0时表示没有错误处理函数,如果非0那么这个参数就指定了错误处理函数在栈中的索引。所以,要记住,如果你想要返回自己定义的错误返回信息,而不是系统的错误返回信息,你应该先把错误返回函数最先压入栈,然后才是调用函数及其参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值