I need to later get the name of the thing that I created with factory.create(). Like, lets say I have a factory that makes circles and another that makes squares. How do I get the from the table?
And you want to store the circles and the squares in the same table? In that case you could store some additional data in the table. Maybe like this:
local shapes = {}
local square_id = factory.create("#squarefactory")
local circle_id = factory.create("#ciclefactory")
table.insert(shapes, { type = "square", id = square_id })
table.insert(shapes, { type = "circle", id = circle_id })
for _,shape in pairs(shapes) do
if shape.type == "square" then
go.set_position(go.get_position(shape.id) + vmath.vector3(100, 0, 0), shape.id)
elseif shape.type == "circle" then
go.set_position(go.get_position(shape.id) + vmath.vector3(0, 100, 0), shape.id)
end
end
Once you get used to them you’ll find that tables are a beautiful multi purpose data structure that is very very easy to work with. I’m more an more surprised every time I see a Hashtable, HashSet and Dictionary in the same language… I mean, what’s the purpose, really? Three datastructures just to get a little bit of utility when a single one would be sufficient…
You could have a script on the game object with exposed custom properties (using go.property) and only store the game object id and use that to query for the exposed properties (using go.get).
But then I’d probably have a single game object type and instead pass additional values when it’s created and use those to get different behaviours from the same game object. And if we convert the above example you’d maybe get something like this:
shape.script:
go.property("type", hash("circle"))
function init(self)
msg.post("#sprite", "play_animation", { id = self.type })
end
foobar.script:
local shapes = {}
local square_id = factory.create("#shapefactory", nil, nil, { type = hash("square") })
local circle_id = factory.create("#shapefactory", nil, nil, { type = hash("circle") })
table.insert(shapes, square_id)
table.insert(shapes, circle_id)
for _,shape_id in pairs(shapes) do
local type = go.get(msg.url(nil, shape_id, "shapescript"), "type")
if type == hash("square") then
go.set_position(go.get_position(shape_id) + vmath.vector3(100, 0, 0), shape_id)
elseif type == hash("circle") then
go.set_position(go.get_position(shape_id) + vmath.vector3(0, 100, 0), shape_id)
end
end