简体   繁体   中英

LuaPlus manipulate table from C++

In this guide functions are created to add a monster to a table and to decrease the health of a monster from the table.

You can easily use the two functons like this from a lua script:

monster = objectMgr:CreateObject("HotMamma",5);
monster:Hurt( 1 ) --decrease health by 1
--or
objectMgr:CreateObject("HotMamma",5);
monster = objectMgr:GetObject(0)
monster:Hurt( 1 )

But how can I call these functions from the C++ side?

I mean the original ones: ObjectMgr::CreateObejct() , ObjectMgr::GetObjectByIndex() and Monster::Hurt()

I spend more than 8 hours on trying to figure this out! But nothing did work. :/

My best try was probably this:

// CreateObject modified to return pMonster and accept normal arguments
MonsterPtr monster = objectMgr.CreateObject(pState, "HotMamma", 5); 
monster.Hurt( 1 );

This gives me the following error:

class "std::tr1::shared_ptr" has no member "Hurt"

From looking at the file Monster.hpp :

class Monster
{
// ...
public:
  Monster( std::string& name, int health );

  void Hurt( int damage );

  void Push( LuaPlus::LuaState* pState );
  int Index( LuaPlus::LuaState* pState );
  int NewIndex( LuaPlus::LuaState* pState );
  int Equals( LuaPlus::LuaState* pState );
};

typedef std::shared_ptr<Monster> MonsterPtr;

MonsterPtr is a C++ shared_ptr . So syntactically, you would have to call Monster's members with -> operator like:

// ...
monster->Hurt(1);

Edit: There seems to be some more setting up involved. The method signature:

int ObjectMgr::CreateObject( LuaPlus::LuaState* pState )

only accepts LuaState * as its only argument and it's not overloaded so the call above in your example isn't going to work. What you'll have to do is push the arguments onto the stack prior to the call. The setup and usage should look something like the following:

LuaObject _G = pState->GetGlobals();
LuaObject name, life;
name.AssignString(pState, "HotMamma");
life.AssignInteger(pState, 5);

_G["objectMgr"].Push();
name.Push();
life.Push();

MonsterPtr monster = objectMgr.CreateObject(pState);
monster->Hurt(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM