1

I am currently trying to do OOP in Lua. From what I've understood here, the instance of a class and even the class ( the variable ) itself are a reference to the various bits and bobs the class holds, so if I have a method :destroy(), consisting of

function class:destroy()
  self = nil
end

when I call instance:destroy() the reference instance should be picked up by the garbage collector and practically, the instance as in an object is gone.

It won't throw up an error or slowly cause a memory leak, right?

EDIT : I thought that maybe I should include the following as well.

This is the method I use to create and instance

function class:new(obj)
  obj = obj or {}
  setmetatable(o,self)
  self.__index = self
  return o
end
Pipi Caca
  • 133
  • 4

1 Answers1

2

Generally, you shouldn't have to do anything to get rid of an instance or any other kind of table. The garbage collector automatically frees the memory of any table that isn't referenced by anything. If you really need to free some memory before a table goes out of scope, simply assign nil to its variable, and the garbage collector will do the rest.

Your destroy method doesn't have any effect, because self is just a parameter (which is a local variable). Assigning directly to it can't affect anything that the caller can see.

luther
  • 5,195
  • 1
  • 14
  • 24
  • So instead of writing a fancy :destroy(), I should just directly do instance = nil ? – Pipi Caca Dec 24 '18 at 21:52
  • Yes, but even that's not necessary unless you know you're short on memory. – luther Dec 24 '18 at 21:55
  • @Bogdan705: Even setting the instance variable to `nil` guarantees nothing. Other people might have a reference to that object, so the object will continue to exist. That's not to say that you *shouldn't* remove references to objects your local code no longer needs, but unless you are certain that nobody else *anywhere* has a reference to it, you shouldn't assume that no such references exist. – Nicol Bolas Dec 25 '18 at 17:58