lua 函数调用的c++封装。 借用了模板,以及同名函数的语言特性实现自动匹配lua函数任意个数参数。
#define MAKE_PUSHER(_type, _functionname) \
void push(lua_State *l, _type data){ \
_functionname(l, data );\
}
MAKE_PUSHER(int, lua_pushinteger)
MAKE_PUSHER(bool, lua_pushboolean)
MAKE_PUSHER(float, lua_pushnumber)
MAKE_PUSHER(double, lua_pushnumber)
// 无参数
int call(lua_State* l, const char* functionname){
cout << "====>" << __LINE__ << " value:" << functionname <<endl;
lua_getglobal (l, functionname);
if ( !lua_isfunction(l, -1)){
fprintf(stderr, " %s not a function", functionname);
return 0;
}
int rs = lua_pcall(l, 0, 1, 0);
// global function must return a integer
if ( !lua_isnumber (l, -1)){
//DLogLuaError( "Global function must return integer" );
lua_pop( l, 1);
return rs;
}
rs = lua_tointeger( l, -1);
lua_pop( l, 1);
return rs;
}
// 1个参数
template <typename T>
int call(lua_State* l, const char* functionname, T t){
auto value = t;
cout << "====>" << __LINE__ << " value:" << value <<endl;
lua_getglobal (l, functionname);
if ( !lua_isfunction(l, -1)){
fprintf(stderr, " %s not a function", functionname);
return 0;
}
push(l, value);
int rs = lua_pcall(l, 1, 1, 0);
// global function must return a integer
if ( !lua_isnumber (l, -1)){
//DLogLuaError( "Global function must return integer" );
lua_pop( l, 1);
return rs;
}
rs = lua_tointeger( l, -1);
lua_pop( l, 1);
return rs;
}
// 2个参数以上
template <typename T>
int call(lua_State* l, const int nArgs, T t){
auto value = t;
cout << "====>" << __LINE__ << " value:" << value <<endl;
push(l, value);
int rs = lua_pcall(l, nArgs, 1, 0);
// global function must return a integer
if ( !lua_isnumber (l, -1)){
//DLogLuaError( "Global function must return integer" );
lua_pop( l, 1);
return rs;
}
rs = lua_tointeger( l, -1);
lua_pop( l, 1);
return rs;
}
template <typename T, typename U, typename ...Args>
int call(lua_State* l,const int nArgs, T&& t, U&& u,Args&&... args){
auto value = t;
cout << "====>" << __LINE__ << " value:" << value <<endl;
push(l, value);
int rs = call(l, nArgs, u, args... );
return rs;
}
template <typename Header, typename Sencond, typename ...Others>
int call(lua_State* l, const char* functionname, const int nArgs,
Header&& t, Sencond&& u, Others&&... others){
auto value = t;
cout << "====>" << __LINE__ << " value:" << value <<endl;
lua_getglobal (l, functionname);
if ( !lua_isfunction(l, -1)){
fprintf(stderr, " %s not a function", functionname);
return 0;
}
push(l, value);
int rs = call(l, nArgs, u, others... );
return rs;
}
// end 2个参数以上