Advertisement

std::Map items as Global Properties

Started by September 27, 2011 02:36 AM
4 comments, last by _orm_ 13 years, 4 months ago
I have an std::map container in my code that maps strings to integers. I want to declare global variables in Angelscript so that the variable names are basically a pointer back to the item in the map. I have been successful doing this with the following code.



typedef std::map<std::string, int> MAPSTR_TO_INT;

void CRTScript::AddVariables(MAPSTR_TO_INT &theMap)
{

std::string itemName;
MAPSTR_TO_INT::iterator it;

for (it=theMap.begin(); it != theMap.end(); it++)
{
itemName.erase();
itemName = "int ";
itemName += it->first;

engine->RegisterGlobalProperty(myPoint.c_str(), &theMap[ it->first]) ;
}
}




I'm just not sure this is the best way to do this. Any thoughts? (No item will ever be deleted from the map so I'm not worried about a dangling pointer.)

What I am actually doing here is equivalent to the following

std::map<string, int> someMap;

someMap['Value1"] = 1;
someMap["Value2"] = 2;


Each of the items will then be registered in Angel script using the code above as

int Value1;
int Value2;


The script can then modify the values
Value1 = 100;
If what you're looking for is global and persistent configuration values, then I can't think of a better way to do it tbh. If that is what you're doing, however, I would recommend using a variant datatype such as boost::any or any number of variant implementations. I actually implemented a rather useful variant in angelscript using a bitstream class I exposed to it which I may move to compiled code as a value type.

A bit more context could help us help you better.
Advertisement
Looking at my post I see my question was not properly stated. What I was really asking was if holding the pointer to an item in an std::map is legal code. I tried to break this with a small piece of code not linked to Angelscript where I inserted a bunch of items in a map. I then got a pointer to one item and deleted all of the other items. I inserted a bunch of other items and it appears that the pointer is still valid. I'm just not positive that it will be all of the time.

I would be interested in any more info you have on variants though. Are you using them with Angelscript?
For a std::map and other node-based standard library containers, holding a pointer to individual elements is legal. Such pointers will only be invalidated when the element is destroyed.
Thanks for the replies. I thought it was legal but at the same time something in the back of my mind was telling me that it might not be.
I am writing a variant for angelscript, yes. One I am sure it works well, I will be posting it here.

This topic is closed to new replies.

Advertisement