I was thinking, Does the 'Destroy' method truly destroy an Instance?
, and, to my surprise, when I tested my Question with a part, it still thought the Instance was existant, even though I called the Destroy
method on it. I am puzzled on why that is, because, I thought the Destroy
method truly Destroyed an Instance. My newest Question now is; Why doesn't the 'Destroy' method truly destroy an Instance?
Here is the code I used in my experiment;
local Part = Instance.new("Part",game.Workspace) if Part then print("Part Existant!") --Prints first time end wait(.1) --Waits .1 seconds Part:Destroy() --Destroys the 'BasePart' instance wait(.1) --Waits another .1 seconds if Part then print("Part Existant!") --Prints again, thus, my question on why the 'Destroy' method does not truly destroy an Instance end
It's because the semantics of Lua make it impossible to "delete" the variable Part
by just calling something on it.
All values, excepting false
and nil
, are "truthy". That means they will pass an if
.
Because of how Lua works,
local obj = {name = "cat"} local same = obj func(obj) print(obj, same)
Now matter what func
is in the top, I can guarantee that obj
is still the same thing after (it still is same
).
That's because while func
can change the value of obj
(for instance, it could change name
to something else) it can't actually change obj
as a variable.
The same is happening with :Destroy()
. It doesn't eliminate the variable,* because you can't do that in Lua*.
Some other languages, e.g., C++, DO allow that sort of behavior. This is for convenience and performance, but usually results in very confusing code. That's why Lua does not allow it.
Part of the purpose of destroy is to mark the object for garbage collection. I'm not exactly sure what the full ramifications of this are.
The other part is simply to prevent it from coming back -- you can't set the parent on a :Destroy()
ed object.
That may or may not help the garbage collector. Ultimately, the purpose may just be to keep good design, rather than for any performance reasons.