Luabind 和C++绑定 关于重载问题的代码
下面是luabind 和C++类的绑定相关用法
C++ 代码
MainFile.cpp
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include <iostream>
#include <string>
#include <luabind/luabind.hpp> //luabind 主要的包含文件
#include "http://www.cnblogs.com/Demo/Help.h"
void greet()
{
std::cout << "greet\n";
}
void greet(long l)
{
std::cout<<"greet "<<l<<std::endl;
}
long greet(long l,float f)
{
std::cout<<"greet "<<l<<" "<<f<<std::endl;
return l;
}
class CBase
{
public:
CBase()
{
printf("CBase::CBase()\n");
}
CBase(long l)
{
printf("CBase::CBase(long l)\n");
}
void Show()
{
printf("CBase::Show()\n %s %d",m_string.c_str(),m_l);
}
void Show(long l)
{
printf("CBase::Show(long l)\n");
m_l = l;
}
void Show(long l,float f)
{
printf("Show(long l,float f)\n");
}
~CBase()
{
printf("CBase::~CBase()\n");
}
std::string m_string;
long m_l;
};
extern "C" int init(lua_State* L)
{
using namespace luabind;
open(L);
/*
// 函数重载写法
// (return_arg-type(*)(arg1-type,grg2-type,...))&function
module(L)
[
def("greet", (void(*)(void))&greet),
def("greet", (void(*)(long))&greet),
def("greet", (long(*)(long,float))&greet)
];
// 成员函数重载用法
// (return_arg-type (classname::*)(arg1-type,grg2-type,...))&classname::class_memberfunction
// 类定义
module(L)
[
class_<CBase>("CBase")
.def(constructor<long>())
.def(constructor<>())
.def("Show",(void(CBase::*)(long))&CBase::Show)
.def("Show",(void(CBase::*)(void))&CBase::Show) //或可以这样写&CBase::Show (这个对于函数重载问题就没法子了)
.def("Show",(void(CBase::*)(long,float))&CBase::Show)
// .def("Show",(void(long))&CBase::Show)
.def_readwrite("m_string",&CBase::m_string) //类的成员数据访问控制 可读写
.def_readonly("m_l",&CBase::m_l) //类的成员数据访问控制 可读写
.enum_("PlayType")
[
value("4K",1),
value("8K",2)
]
];
*/
return 0;
}
void main()
{
USER_Try
lua_State* L = lua_open();
// 加载常见的Lua 库
luaL_openlibs(L);
init(L);
luaL_dofile(L,"test.lua");
/*
luabind::call_function<int>(L,"Test");
std::cout<<"Test Ok!"<<std::endl;
*/
while(true)
{
luabind::call_function<int>( L ,"TestRun");
getchar();
}
lua_close(L);
USER_Catch_Exception;
}
Help.h
#define USER_Try try{
#define USER_Catch_Exception }\
catch(luabind::error e)\
{\
std::cout<< e.what()<<std::endl;\
}\
catch(luabind::cast_failed e)\
{\
std::cout<<e.what()<<std::endl;\
}\
catch( ... )\
{\
__asm{ \
int 3 \
} \
}
浙公网安备 33010602011771号