在C++中调用lua函数

1.代码示例


#include "stdafx.h"

#include <iostream> 
#include <luabind/luabind.hpp>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	lua_State *L = ::luaL_newstate();  /* opens Lua */
	luabind::open(L);

	luaL_dostring(L,"function add(first,second)\n return first + second\n end\n");
	  
	try{
		std::cout<<"Result:"
			<<luabind::call_function<int>(L,"add",2,3)<<std::endl;
	}
	catch(luabind::error& e){
		std::cout<<"catch exception:"<<e.what()<<std::endl;
	}
	

   lua_close(L); 
     	
}



2.基本函数解读

a.luaL_newstate()

建立lua环境

b.luabind::open

连接lua stateluabind,让luabind认识这个lua环境

c.luaL_dostring

添加lua函数到lua环境

d.luabind::call_function

这个函数的的第一个模板参数是传入的要调用的lua函数的返回值类型,也就是lua函数funciont add的返回值类型

。该函数的其余模板参数由C++模板函数的机制推倒出来。函数的第一个参数是包含function addlua state,第二个参数是函数名称,接下来就是函数参数了。

e.头文件

luabind的使用中不需要包含lua.h之类的文件如:extern "C"{ #include  "lua.h"}

只需要包含luabind/luabind.hpp即可支持类和函数的注册


参考网站:点击打开链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值