I am programming in squeak and need to compare two blocks of code as follows: (toRunBlock is an instance variable)
~~~Other code~~~
toRunBlock := [nil].
~~~Other code~~~
But at some point, I need to compare it to another block of code:
(toRunBlock = [nil]) ifTrue: [
"Run some code if toRunBlock hasn't been overwritten"
].
But that check is always giving false, and I can't find a way to check if they're equal. Can someone help me out with this?
As @LeandroCaniglia pointed out, you shouldn't have to compare blocks. Here are two ways to solve your problem without comparing blocks:
initialize the variable to nil
. In your accessor method you initialize it lazily:
toRunBlock
^ toRunBlock ifNil: [ [] ]
Now, when you look at the variable toRunBlock
it will be nil
unless #toRunBlock
has been sent or the block as been set by other means.
Your code would become:
toRunBlock ifNil: [
"Run some code if toRunBlock hasn't been overwritten"
].
use additional state by setting an instance variable you can check. This could be your setter method for example:
toRunBlock: aBlock
toRunBlock := aBlock.
hasToRunBlockBeenSet := true
And to check you could use a method like this:
hasToRunBlockBeenSet
^ hasToRunBlockBeenSet ifNil: [ false ]
Your code would become:
self hasToRunBlockBeenSet ifTrue: [
"Run some code if toRunBlock hasn't been overwritten"
].
The second method is arguably more reliable.