[4.51] Using @ to get pointer while creating new map element

Just starting out? Need help? Post your questions and find answers here.
cxAlex
User
User
Posts: 88
Joined: Fri Oct 24, 2008 11:29 pm
Location: Austria
Contact:

[4.51] Using @ to get pointer while creating new map element

Post by cxAlex »

German thread:
http://www.purebasic.fr/german/viewtopic.php?t=23835

If you are using @ to get the pointer to a map-element while creating it, the map element is not created.

Code: Select all

NewMap myMap.i()

Debug @myMap("haha")

ForEach myMap()
Debug MapKey(myMap())
Next
Working:

Code: Select all

NewMap myMap.i()

myMap("haha")
Debug @myMap()

myMap("lol")
Debug @myMap()

ForEach myMap()
Debug MapKey(myMap())
Next
Greets, Alex
User avatar
Demivec
Addict
Addict
Posts: 4258
Joined: Mon Jul 25, 2005 3:51 pm
Location: Utah, USA

Re: [4.51] Using @ to get pointer while creating new map ele

Post by Demivec »

cxAlex wrote:If you are using @ to get the pointer to a map-element while creating it, the map element is not created.
Here is documentation from AddMapElement() in the Map library:
This function isn't mandatory when dealing with maps, as elements are automatically added when affecting a value to them.
I would deduce that you didn't create a map-element because you didn't affect a value to it. You can't get the address of a new map element with the @ operator at the time of assignment because the @ operator cannot be used on the left side of the equation (i.e. can't use '@myMap("lol") = 3') and this isn't syntactically correct for any portion of the left side of an equation either.

The proper way would be to use the AddMapElement() command because it performs the assignment/creation and returns the address.

Code: Select all

NewMap myMap.i()

Debug @myMap("haha") ;element hasn't been assigned anything, thus not created yet
Debug AddMapElement(myMap(),"lol") ;this is the correct way to create a map element and return its address

ForEach myMap()
  Debug MapKey(myMap())
Next
By the way, the address that is returned for an uncreated element is always the same, no matter what the key is. I am not sure what the address points to. I think that is a bug that probably needs to be addressed. I would suggest it = 0 if the element doesn't exist.
User avatar
IceSoft
Addict
Addict
Posts: 1682
Joined: Thu Jun 24, 2004 8:51 am
Location: Germany

Re: [4.51] Using @ to get pointer while creating new map ele

Post by IceSoft »

It works if you set a 'default' value calling myMap("haha") before you start the foreach

Code: Select all

NewMap myMap.i()

Debug @myMap("haha")
myMap("haha")

myMap("lol")
Debug @myMap()

ForEach myMap()
  Debug MapKey(myMap())
  Debug myMap()
Next
Belive! C++ version of Puzzle of Mystralia
<Wrapper>4PB, PB<game>, =QONK=, PetriDish, Movie2Image, PictureManager,...
Post Reply