How to pass string or table to a factory created object?

For simple numeric data some approach as below could be used

local col = vmath.vector4(math.random(), math.random(), math.random(), 1)
factory.create("#factory", nil, nil, { color = col })

-- object.script
go.property("color", vmath.vector4())
function init(self)
   go.set("#sprite", "tint", self.color)
end

Multiple values if they are number can be added to that table too

local data = { size = 10, cost = 100 }
factory.create("#factory", nil, nil, data)

-- object.script
go.property("size",  1)
go.property("cost", 10)

function init(self)
   -- process data
end

But what to do with strings data? How do you pass it to such objects? What about some data that is table itself?

One thing I can think of it is to send message with the data. And process this message in the object.script. Is this the right approach?

local data = { size = 10, tooltip = "some tooltip" }
local url = msg.url(nil, factory.create("#factory", nil)
msg.post(url, "data_init", data)

-- object.script
function on_message(self, message_id, message)
   if message_id == hash("data_init") then
        self.data = message
       pprint(self.data.tooltip)
    end
end

How you would then retrieve this data at runtime? With another pair of messages?

-- object.script
function on_message(self, message_id, message, sender)
    if message_id == hash("data_request") then
        msg.post(sender, "data_response", { item = self.data[message.item] })
    end 
end

Am I overthinking this?

Hi,

This is pretty much what I do. Strings cannot be passed when you factory create the object as the type is not supported as a game object property, only hashes of strings are. So if your string is something you need as a string - to display it for example - you need to use messaging.

Basically, everytimes I have to change something to an instancied object after creation, I make its script receive a message, added with reading a table for details.

Try use global variable

You could also consider to use a module that holds tables of data for each object, and just give an id to the factory, and let the object look up the data in the module from that id.

2 Likes

@Halfstar yes that’s an interesting solution. More so than global variables. What I like about messaging though is that the message handler can perform some actions - initializations, animations, sounds, etc… - upon receiving the data the object needs. Passing values via global variables or data module remains static.