在脚本中使用类的成员函数
#include "luaplus.h"
using namespace LuaPlus;
template< class T >
class LuaExport
{
public:
LuaExport(const char* pszName, LuaPlus::LuaState* pState = 0)
{
//TDAssert(s_pMe == 0);
s_pMe = static_cast< T* >(this);
LuaPlus::LuaState* theState = pState; //? pState : CScriptSystem::_GetLuaState();
s_pMetaTable = new LuaPlus::LuaObject;
*s_pMetaTable = theState->GetGlobals().CreateTable(pszName);
s_pMetaTable->SetObject("__index", *s_pMetaTable);
LuaObject obj = theState->BoxPointer(s_pMe);
obj.SetMetaTable(*s_pMetaTable);
theState->GetGlobals().SetObject(pszName, obj);
}
virtual ~LuaExport()
{
delete s_pMetaTable; s_pMetaTable = 0;
s_pMe = 0;
}
template <class Callee>
void RegisterFunction(const char* pszFuncName, int (Callee::*func)(LuaPlus::LuaState*))
{
s_pMetaTable->RegisterObjectFunctor(pszFuncName, func);
}
//取得自己
static T* GetMe(void) { return s_pMe; }
protected:
static T* s_pMe; //自身实例,全局变量
static LuaPlus::LuaObject* s_pMetaTable; //MetaTable
private:
// unimplemented constructors / assignment
LuaExport(const LuaExport& obj);
LuaExport& operator=(const LuaExport& obj);
};
extern LuaPlus::LuaState* GetLuaState(); // 测试main.cpp
class player : public LuaExport< player >
{
public:
player():
LuaExport< player >( "pp", GetLuaState() )
{
}
int LS_PrintNumber(LuaState* state)
{
LuaStack args(state);
if (args[2].IsNumber()) {
printf("%f\n", args[2].GetNumber());
}
else if ( args[2].IsString() )
{
printf("%s\n", args[2].GetString() );
}
return 0;
}
int UI_SetTipText( lua_State *state )
{
LuaStack args(state);
if ( args[2].IsString() )
{
const char *szData = args[2].GetString();//lua_tostring(state, 1);
if( szData )
{
printf("%s\n", szData );
}
}
return 0;
}
};
player* LuaExport< player >::s_pMe = 0;
LuaPlus::LuaObject* LuaExport< player >::s_pMetaTable = 0;
int _tmain(int argc, _TCHAR* argv[])
{
player* pPlayer = new player();
pPlayer->RegisterFunction( "PrintNumber", &player::LS_PrintNumber );
pPlayer->RegisterFunction( "SetTips", &player::LS_PrintNumber );
// Register your functions.
int nRet = GetLuaState()->DoFile( "main.lua" );
if ( nRet )
{
printf("错误信息: %s", GetLuaState()->StackTop().GetString());
}
getchar();
return 0;
} // main.lua
pp.PrintNumber(1000)
1.需要注意的是,类的成员函数中的参数 默认第一个为this
所以 要活得参数的时候 下标默认加1
if (args[2].IsNumber())
{
printf("%f\n", args[2].GetNumber());
}
posted on 2011-07-18 13:27
风轻云淡 阅读(1245)
评论(0) 编辑 收藏 引用 所属分类:
LuaPlus