Firstly, for @ConveyedRex7592, I already explained how you’d access display objects that have been added to a table. For instance, if you added them to a table using number keys, then you’d just refer to them like object[1].x = object[1].x + 10
.
It really seems like you would benefit from some tutorials. This isn’t a criticism, this is just me trying to help you out. Take a look at https://docs.coronalabs.com/tutorial/ (especially the Getting Started Guide). I feel like you’d benefit greatly from going through that.
@Odisej That link provides a lot of good tips, but there are some mistakes, typos and oversights, especially with tip #8.
This is a bit off topic, but, for instance, the spawnAGuy
“Best example”, would crash if a table isn’t passed to the function. Making it crash proof would be as simple as:
local function spawnAGuy(params)
local params = params or {} -- if params isn't passed, create an empty table.
local guy = display.newImage("guy.png")
guy.x = params.x or 100 -- without params table, this line would crash.
guy.y = params.y or 100
if params.group then
params.group:insert(guy) -- there was a typo here.
end
return guy
end
Now, we can remove the display objects even if we don’t return anything from the function by simply removing the display group that they are added to. This happens because Lua’s garbage collector will remove objects from memory if they no longer have a reference to them. If we don’t explicitly assign a reference to the display objects that we create, then there will only be a reference to them in the display.group (or stage) that they are added to.
In either of my two examples above, whether you remove all direct references or just the display group where the objects are, the memory footprint will be the same.
Now, finally, there’s another big issue with tip #8 concerning the destroy()
method. Here’s a simplified version of it:
local function spawnARect()
local rect = display.newRect(100,100,100,100)
function rect:destroy()
display.remove(self)
self = nil
end
return rect
end
local spawnedRect = spawnARect()
spawnedRect:destroy()
print( spawnedRect ) -- It still exists even though we just destroyed it?
This is actually something that I was asking about for myself last year or the year before that, so we are all continually learning.
The problem with this method is that it while it can remove the display object via a refence to itself, it cannot set itself to nil because of how tables work in Lua. Essentially, self
is another reference to the same display object (table) as with spawnedRect
. However, in Lua, you must explicitly set each reference to a table to nil before the table actually becomes nil.
In other words, the destroy()
method sets a reference to the display object that only exists within the function to nil, but it doesn’t affect the references outside of the function at all. Now, there are ways to get it to properly destroy itself, but I’ve already rambled far too long about this off-topic issue.