Your teacher? Why isn’t your teacher helping with this?
I’m sorry if you’re not getting sufficient help from your teacher, that bites.
… to the question
The use of the term ‘name’ doesn’t make any sense in this context. Anything you use as an index in a table must be unique or you are referencing the same position in the table.
So, if you did this:
local objs = {} objs["obstacle"] = display.new...() objs["obstacle"] = display.new...()
You will have created two objects, but only one (the last one created) will be referenced in the table.
Perhaps, your teacher meant or said, ‘reference objects by their ID’.
local objs = {} local tmp = display.new...() objs[tmp] = tmp local tmp = display.new...() objs[tmp] = tmp
The table above has two unique entries, each referencing one of the two created objects.
However, because you used non-numeric indices, you have to iterate over the table like this:
for k,v in pairs( objs ) do ... do some work on the objects here v is the object k is the index end
For a concrete example, lets change the color of all objects in the table to red:
for k,v in pairs( objs ) do v:setFillColor(1,0,0) end
Now, lets apply the ID concept. Let’s add a few objects and set pickups to yellow and obstacles to red:
local objs = {} -- make two pickup objects local tmp = display.new...() tmp.id = "pickup" objs[tmp] = tmp local tmp = display.new...() tmp.id = "pickup" objs[tmp] = tmp -- make two obstacle objects local tmp = display.new...() tmp.id = "obstacle" objs[tmp] = tmp local tmp = display.new...() tmp.id = "obstacle" objs[tmp] = tmp
later…
for k,v in pairs( objs ) do if( v.id == "pickup" ) then v:setFillColor(1,1,0) elseif( v.id == "obstacle" ) then v:setFillColor(1,0,0) end end
What about removing objects from the table?
I’m going to use the collision code I provided in a prior post and assume that all objects are in the table objs and that objs is visible in the collision listener.
If all that is true, I can do this:
-- somewhere above the listener local score = 0 local objs = {} function player.collision( self, event ) local phase = event.phase local other = event.other -- thing player collided with if( phase == "began" ) then if( other.id == "obstacle" ) then -- do whatever you are supposed to with obstacles here elseif( other.id == "pickup" ) then -- lets increment the score, delete the pickup object, and remove it from the tracking -- table score = score + 1 display.remove(other) objs[other] = nil elseif( other.id == "danger" ) then -- do whatever you are supposed to with dangers here end end return false end player:addEventListener( "collision" )