LuaPlus学习(四)

<--!版权所有foruok,转载注明出处!-->

一个完整的例子

试验了一个完整的例子。 在C++中生成一个类,注册到lua。 从lua调用C++类的成员函数。 在Alternate.lua中写了阶乘函数factorial。 从C++中调用factorial。 Alternate.lua如下:
print( " nowinalternate.lua " ); print( " initialnumberofAxhSystem: " ..AxhSystem:GetNumber()); AxhSystem:SetNumber( 15 ); print( " Changethenumberfromlua,new: " ..AxhSystem:GetNumber()); print( " NowSetmessageto'Helloworld' " ); AxhSystem:SetMessage( " Helloworld " ); print( " AxhSystem:GetMessagereturn: " ..AxhSystem:GetMessage()); print( " now,enteranumbertochangeAxhSystem'snumber: " ); num = io.read( " *number " ); print( " youenter: " ..num); print( " settoAxhSystem " ) AxhSystem:SetNumber(num); print( " AxhSystem'snewnumber= " ..AxhSystem:GetNumber()); functionfactorial(n) if (n == 0 )then return 1 ; else return n * factorial(n - 1 ); end end
C++代码如下:
class CAxhSystem ... { public: CAxhSystem():m_nNumber(0) ...{ memset(m_szMsg,0,sizeof(m_szMsg)); } ~CAxhSystem() ...{ } voidSetNumber(intnum) ...{ m_nNumber=num; } intGetNumber() ...{ returnm_nNumber; } voidSetMessage(constchar*szMsg) ...{ if(szMsg) _tcsncpy(m_szMsg,szMsg,256); } char*GetMessage() ...{ returnm_szMsg; } protected: intm_nNumber; charm_szMsg[256]; } ; CAxhSystemg_system; LuaStateOwnerg_state; LuaObjectg_globalObj; int InitLua() ... { g_state->OpenLibs(); g_globalObj=g_state->GetGlobals(); return0; } int RegisterObject() ... { LuaObjectaxhmetaobj=g_globalObj.CreateTable("AxhMetaTable"); axhmetaobj.SetObject("__index",axhmetaobj); //registerfunctor axhmetaobj.RegisterObjectDirect("SetNumber",(constCAxhSystem*)0,CAxhSystem::SetNumber); axhmetaobj.RegisterObjectDirect("GetNumber",(constCAxhSystem*)0,CAxhSystem::GetNumber); axhmetaobj.RegisterObjectDirect("SetMessage",(constCAxhSystem*)0,CAxhSystem::SetMessage); axhmetaobj.RegisterObjectDirect("GetMessage",(constCAxhSystem*)0,CAxhSystem::GetMessage); //getluaobject LuaObjectluasys=g_state->BoxPointer(&g_system); luasys.SetMetaTable(axhmetaobj); g_globalObj.SetObject("AxhSystem",luasys); return0; } int _tmain( int argc,_TCHAR * argv[]) ... { InitLua(); RegisterObject(); g_state->DoFile("Alternate.lua"); LuaFunction<int>factorial=g_state->GetGlobal("factorial"); printf(" Nowcall'factoral'inAlternate.lua,enteranumber:"); intnumber; scanf("%d",&number); printf("Youennter%d,it'sfactorial=%d ",number,factorial(number)); return0; }
OK,到这里已经可以在lua和c++之间做一些交互了,可以根据需要实现我们的目标了。 接下来我要好好学习lua了,不然没办法用它来写复杂的逻辑。 <--!版权所有foruok,转载注明出处!-->

你可能感兴趣的:(lua)