[RGSS] SELF.DESTROY

Posts

Pages: 1
Hello all,

Is there a way for objects to destroy themselves using the self-referential "self"? Code that achieves the effect of "self = nil"?
Trihan
"It's more like a big ball of wibbly wobbly...timey wimey...stuff."
3359
You can use self.dispose, but the object obviously has to have a dispose method for this to work.
Is there a way to code that into homemade classes? Let me type an example:


class My_Class
def initialize(timer, sprite_name)
@timer = timer
@sprite = Sprite.new
@sprite.bitmap = RPG::Cache.pictures(sprite_name)
end

def update
@timer -= 1
if @timer < 1
self.dispose
end
end

def dispose
@sprite.dispose
# ??? Could anything else go here to completely
# get rid of this My_Class object from memory?
end
end

Actually, I just realized that you don't need the "self", just write "dispose"... Why does "self" exist if you can just reference the method that's already there?
Trihan
"It's more like a big ball of wibbly wobbly...timey wimey...stuff."
3359
Yeah, your example is pretty much there. Just do @sprite = nil after the call to dispose and you're golden.

For the most part, you're right: self is mostly redundant. It can help to disambiguate between class methods, instance methods and local variables, though.

Let's say you have a class with an instance variable "some_var", and the class also has a method which takes a parameter, also called "some_var". If you need to do something to both of them in the same method, you're going to run into an issue:

some_var = whatever
some_var = whatever else

This is going to perform both operations on the local variable. However...

self.some_var = whatever
some_var = whatever else

This will assign whatever to the instance variable and whatever else to the local variable.

You'll find in a lot of cases in the VX Ace default scripts, the references to self are mainly just there to clarify that methods can be called by a class without having an instance, or to avoid confusion when the variable is named something you might mistake for a local variable in the context of the method.
In addition to what Trihan said, self is useful when an object needs to call a function with itself as an parameter. It can also be used as a return value, allowing you to call multiple methods in a single line of code.
Pages: 1