Types help us to know how to use a variable
We saw different data types and even know how to create our own. But there was one big problem! Variables could change type mid-execution. This is particularly annoying because if we use the wrong type of data in a certain situation, the game will crash!
var number_of_lives = 5 number_of_lives += 1 number_of_lives = { player_lives = 5, enemie_lives = 1, } number_of_lives += 1
In the preceding code, the first marked line will work, but the second one crashes the game! This crash happens because, in the first instance, we add 1
to the value 5
, another number, while in the second instance, we try to add 1
to a whole dictionary. This operation is not supported and thus crashes the game.
Luckily, there is a way we can leverage our knowledge of what data type we expect for certain operations or functions. This is what we will learn over the course of this section.