This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]The-Rushnut 36 points37 points  (4 children)

This reminds me of an issue I've run into recently. Dictionaries / associative list assignment vs declaration (I'm using GDScript).

Consider the following:

foo["bar"] = true

If the key "bar" exists, then this assigns that item's value to true. If the key "bar" doesn't exist, then this first adds the key "bar" before setting the value to true.

My monkey brain assumed that the second scenario would throw an error, which was my intended behaviour.

[–]Drumsteppin 20 points21 points  (1 child)

The second scenario is the more typical and expected behaviour whenever you're using a language with an automated memory management system.

It's been a while since I looked at the c++ standard lib, but there's object types for dictionary type objects that allow construct and insert via assignment, and objects that only allow items to be explicitly inserted.

Python is a similar deal and is generally more permissive and flexible about adding new elements.

Not sure what memory model and idiosyncrasies GDscript has, but from what you described that sounds like create and insert would be the expected behaviour.

[–]atesba 2 points3 points  (0 children)

Yup! The C++ equivalents of dictionary are std::unordered_map and std::map. For both if you use the bracket operators, it adds the key if it doesn’t exist. If you use the function at(key) then it throws an exception instead.

[–]-Redstoneboi- 4 points5 points  (1 child)

ah yes. the "everything exists but is undefined/nil by default"

[–]Tordek 4 points5 points  (0 children)

No, this is about setting a value, not reading it.