Game Development Community

Strange results with ConsoleMethod and Variables

by Michael K. · in Torque Game Engine · 10/26/2007 (7:51 am) · 3 replies

Hi,

i'm using Ben Garney's Commander Map.

Now i want to expand it with some new features, etc. but i'm having some strange results.

I'm trying to create two console methods "addHotObject" and "viewHotObject".

Here's some code extracts:

-------------------------------------------------------------------------------------

class GuiCommanderHud : public GuiTSCtrl
{

...

public:
const char * mHotPOIObject;

void GuiCommanderHud::setHotObject(const char * mHotObject_tmp);
const char * GuiCommanderHud::getHotObject();

...

}

void GuiCommanderHud::setHotObject(const char * mHotObject_tmp) {
mHotPOIObject = mHotObject_tmp;
}

const char * GuiCommanderHud::getHotObject() {
return mHotPOIObject;
}

ConsoleMethod(GuiCommanderHud, addHotObject, void, 3, 3, "(val) Defines the HotObject.")
{
object->setHotObject(argv[2]);
// Print HotObject
Con::printf("New HotObject: %s ", object->getHotObject());
}

ConsoleMethod(GuiCommanderHud, viewHotObject, const char *, 2, 2, "Shows/Returns the HotObject.")
{
// Print HotObject
Con::printf("View HotObject: %s ", object->getHotObject());
return object->getHotObject();
}

-------------------------------------------------------------------------------------

so what's my problem? Well, when i call the Console Method PlayerMapHud.addHotObject("Something"); the console outputs "New HotObject: Something", which is exacly what i want it to do... BUT if i type PlayerMapHud.viewHotObject(); the console shows "View HotObject: ", the variable mHotPOIObject is empty (?), sometimes it also outputs "View HotObject: " and shows all kinds of things for mHotPOIObject...

What did i do wrong?

Thanks alot!
Mike :-)

#1
10/26/2007 (9:42 am)
Console functions and methods that return strings seem to use the Con::getReturnBuffer system.

Since you probably want to return a copy of the value anyway, rather than giving the script engine your existing pointer, you might try this and see if it solves the problem.
#2
10/26/2007 (9:46 am)
It doesn't look like you're actually storing the string anywhere. So in the addHotObject, the pointer is still valid, so you get what you expect. In the viewHotObject function mHotPOIObject now points to random space...

One solution is to use:
const char *objectName = dStrdup(argv[2]);
object->setHotObject(objectName );
[If you do this, make sure you free mHotPOIObjectin your class's deconstructor, or you'll have a memory leak.]

Another solution is to use a StringTableEntry instead like this:

public:
StringTableEntry mHotPOIObject;
...
StringTableEntry objectName = StringTable->insert(argv[2]);
object->setHotObject(objectName );
This will never be freed.
#3
10/27/2007 (12:17 am)
That did it!

Thanks alot