Sending functions through messages

Is it possible to send a function to another script in a msg.post() call? It seems to be an unsupported data type, because I get the error

unsupported value type in table: function

when it tries to send it. My use case is this: I have a “bullet” object, with values assigned to it when it is created from a factory. It has a lifespan, velocity, position, etc. but I would also like to be able to give it a callback function from another script (the script that created it), so that when it’s lifespan runs out, it might, for example, tell the factory to create another bullet of the same type with a different lifespan, direction, callback, etc. I have a lua module for the generic bullet-related functions, and I want it to be as robust as possible, but I can’t see any way of doing what I want without creating duplicate bullet objects with slightly different callbacks. Any help?

The function in question is this (from the bullet-prototype lua module)

bulletProto.newBullet = function(factory_url, position, direction, speed, lifespan, callback)		
	thisBullet = factory.create(factory_url, position, vmath.quat_axis_angle(vmath.vector3(0, 0,1),math.atan2(direction.y,direction.x)), {direction = direction, speed = speed, lifespan = lifespan})	
	msg.post(thisBullet, 'callback', {callback = callback})
end

that’s right, it’s not supported. However in your case, there is a workaround: send a message with all of the relevant properties to the spawning object, and then in the on_message behaviour, get it to spawn a new bullet with those properties.

1 Like

Hmm, that would probably work. Thanks for the quick reply!

Would it work to have a lua module for each bullet-type, then assign different functions to different keys in the module, and send the key to the object to access the correct function in the module? That way I could create whole functions to be used on the expiration of the object, rather than just a spawn command, and I could bypass the message-system alltogether.