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 state到luabind,让luabind认识这个lua环境
c.luaL_dostring
添加lua函数到lua环境
d.luabind::call_function
这个函数的的第一个模板参数是传入的要调用的lua函数的返回值类型,也就是lua函数funciont add的返回值类型
。该函数的其余模板参数由C++模板函数的机制推倒出来。函数的第一个参数是包含function add的lua state,第二个参数是函数名称,接下来就是函数参数了。
e.头文件
luabind的使用中不需要包含lua.h之类的文件如:extern "C"{ #include "lua.h"}
只需要包含luabind/luabind.hpp即可支持类和函数的注册
参考网站:点击打开链接