Page 1 of 1

Does table.remove remove the item from memory?

Posted: Wed Dec 08, 2021 2:05 am
by chicohaze
Hi,

I'm new to LÖVE and new to Lua. I have a question about table.remove.

Say I'm tracking a bunch of enemies in a table and I want to destroy one. When I do table.remove(enemies, i), does it destroy that the enemy object and remove it from memory, or does it just remove it from the enemies table?

Re: Does table.remove remove the item from memory?

Posted: Wed Dec 08, 2021 3:55 am
by BrotSagtMist
No, It does not immediately run the garbage collector if thats what you mean, but will be removed _whenver needed_.
But garbage collection is nothing you should worry about, it will run timely.
If the data in that field are all normal lua values, numbers and tables its almost impossible to create any significant ram usage anyway.
There are however data types that are not automatically cleared without explicitly calling a garbage collect. Like for example if each _enemy_ has its name displayed in its own custom font this font would stay in ram even if its not referenced anymore.

If you feel your game is taking too much ram you can issue a manual collection "collectgarbage ()" and check if that changes the ram usage.

Re: Does table.remove remove the item from memory?

Posted: Wed Dec 08, 2021 5:01 pm
by milon
See https://www.lua.org/pil/19.2.html for details on table.remove - it's a Lua function, not Love specific.

If i is a basic string/number (unlikely in this case), then its data is lost immediately.

If i is a table or other object, the reference is removed from the enemies table. If you have another variable already pointing at enemies{i}*, the data will still exist and be accessible from that other variable (but not in the enemies table). Garbage collection (IIRC) only releases memory that has no valid pointers. Rule of thumb: if you execute print(variableName) and get a generic label followed by a hex string, then variableName is a pointer to an object, and as such you can have multiple pointers pointing to it.

Hope that was helpful!

* Using curly braces so it doesn't italicize my post