David D
David D

Reputation: 113

Set the value of an object from inside a method in Io

I'm trying to set the value of an object from inside a method. Here's an example:

myObject := list(1,2,3,4,5)

myObject drop := method(
    self := list()
)

myObject drop
myObject println //returns original object

What am I doing wrong?

Upvotes: 1

Views: 87

Answers (1)

jer
jer

Reputation: 20236

What you've done is create a new slot inside the method and named it self. Which means it goes away when the method returns. In Io self isn't a keyword, there are no keywords, and thus it doesn't have special meaning.

What you're looking for is to use a method that modifies self. Since List is written in C, you'd have to interface directly with something written in C, or with something that interfaces with something written in C, to clear the contents of the list. Consider:

myObject drop := method(
    self empty
)

What's going on here is List has a method named empty which removes all items and returns the now empty object. It talks to a primitive List method called removeAll to accomplish this.

This is a bit cut and dry though. In the general case, in other circumstances, you may want to save the item you want to return BEFORE you remove it from the collection. i.e.,

myCollection drop := method(
    result := self at(42)
    self removeAllTheThings
    result
)

Since not every type of collection that could exist, would have a removeAll or empty method built in.

Upvotes: 1

Related Questions