Search code examples
event-handlingsmalltalksqueak

Accessing instance variables in an eventhandler with smalltalk


I'm pretty new to smalltalk and an apparently easy problem drives me crazy. My own class inheritates from the Morphic class and overwrites keyStroke

keyStroke: anEvent
Transcript show: myDigitClass.
(((anEvent keyValue) > 47) and: ((anEvent keyValue) < 58)) ifTrue: [
    "myDigitClass dropADigit"
    "myDigitClass setADigit: (anEvent keyValue) asCharacter."
    Transcript show: (anEvent keyValue) asCharacter
    ]

that works so far and the Transcript shows me my input I made on the keyboard but the instance variable myDigitClass is NIL even though I initialised this variable and passed it through a setter-method to this class. If access myDigitClass by a getter-method I wrote it works.

I call the showPane method and assign the input param digitMD to the instance Var.

showPane: digitMD
  |pane|
  myDigitClass := digitMD.

  pane := DigitMorph new.
  pane extent: 340@340.
  ^pane openInWorld.

And in the Workspace I do the following:

 myDigitClass := DigitClass new.
 myTest := DigitMorph new.
 myTest showPane: myDigitClass.

Solution

  • You can access instance variables directly by sending the object #instVarNamed:. This is a private method though and should only be used if you know what you are doing, or for debugging.

    You would use #instVarNamed: in your example the following way, assuming the instance variable of your class is called theDigit:

    ...
    Transcript show: (myDigitClass instVarNamed: 'theDigit').
    ...
    

    The transcript will show the value effectively stored (e.g. nil).