How two objects should be compared depends on your situation. There are two ways of asking the question: do the objects hold the same value, or are the objects actually the exact same object. To understand the difference, consider two colors:
$blue = Color.newWithRGB(0, 0, 1)
$favorite = Color.newWithRGB(0, 0, 1)
These two colors are equal in value as they display exactly alike. However, they are not actually the same color object. If $favorite is modified it does not change the value of $blue:
$blue = Color.newWithRGB(0, 0, 1)
$favorite = Color.newWithRGB(0, 0, 1)
$favorite.green = 1 # turn green on to make a cyan
# blue is still just blue
On the other hand, it’s possible two variables both refer to the exact same color:
$blue = Color.newWithRGB(0, 0, 1)
$favorite = $blue
$favorite.green = 1 # uh oh, $blue is cyan now
Here only one color is constructed, but both $blue and $favorite refer to it. They represent the same object. If we make a change to one variable, it appears as if the other variable automatically changed as well, since they actually refer to the same underlying object. To overcome this intertwining use the copy command:
$blue = Color.newWithRGB(0, 0, 1)
$favorite = $blue.copy
$favorite.green = 1 # turn green on to make a cyan
# blue is still just blue
When using the equality operators (== and !=) the object itself determines how the comparison is made, in a way that is most natural to the type of object. Usually this comparison is by value. For example, Text objects compare based on the characters they contain:
$text = 'sky'
$other = 'sky'
If $text == $other
Prompt "Yes, the text is the same."
End
However, sometimes it may be helpful to know if the underlying object is actually the same, not just that the current value is equal:
.isSameObject otherObject v1.3
Returns @true if both objects are the exact same object, otherwise @false.
Going back to colors, this command can differentiate two color objects, even if they display the same:
$blue = Color.newWithRGB(0, 0, 1)
$other = Color.newWithRGB(0, 0, 1)
$isEqual = $blue.isSameObject($other) # @false, there are two colors
Previous Chapter Object Overview |
<< index >> |
Next Chapter Dynamic Properties and Commands |