How to insert an object created by a function in a table?

Hello, I’m trying to do this simple thing to learn solar2d. I want to insert in a table an object created by a function.

t={}
local function spawnObj(self)
obj= display.newImageRect(“obj.png”)
physics.addBody( obj, “dynamic”,{ density=1, bounce=1 })
end
end

I tried to table.insert( t, obj ) but It’s not working. This function is called every time there is a collision event. I want the spawned object to be inserted in the table t. I want to be able to remove the object with a tap after so I have to be able to access the table and its children. So each obj created by the function needs to have its own “identity”.
Thank you in advance.

Try adding Return obj in your function. Then local myObj = spawnObj() and table.insert( t, myObj ) or t[i] = spawnObj()

1 Like

maybe this can help:
t={}
local function spawnObj(self)
local obj= display.newImageRect(“obj.png”)
physics.addBody( obj, “dynamic”,{ density=1, bounce=1 })
t[#t + 1] = obj
end
end

Thank you.