1

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"

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Forivin
  • 14,780
  • 27
  • 106
  • 199

1 Answers1

2

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);
greatwolf
  • 20,287
  • 13
  • 71
  • 105
  • @Forivin I've added some more info about `objectMgr.CreateObject` in case you run into problems calling it from C++. – greatwolf Nov 01 '13 at 14:05
  • Well, I modified CreateObject to accept normal arguments. So monster->Hurt(1); actually did the job. :p I couldn't call it from the Lua side afterwards anymore though.. So I will definitely check this out! Thanks thanks thanks. :) – Forivin Nov 01 '13 at 14:08
  • I'm just wondering if I could put all created monsters in an array. Since the type MonsterPtr doesn't seem to have array support by default – Forivin Nov 01 '13 at 14:11
  • I don't see why not. `class ObjectMgr` actually has a `std::vector< MonsterPtr > m_objectList;` if you look. – greatwolf Nov 01 '13 at 14:15