Creating Seperate Lua Modules for Game Object Instances

Part of my game involves me using a factory to create instances of a game object (a boat). The scripts I have written for the game object all reference a Lua Module that exists to store variables that all the scripts need. Unfortunately, every time I create a new instance of the boat game object, it shares the same variables module as the others which creates conflicts and issues.

How could I create a seperate variables module for each game object instance?
or would it be better for me to pursue a different method of storing variables globally across scripts?

This variables module looks a bit like this:

local M = {}

M.velocity= vmath.vector3()

function M.modifyvelocity(value)
	M.velocity= value

end

return M

Thanks

You could store multiple velocities in the table, and have it indexed by the id of each individual gameobject (go.get_id()).

Just as an example:

local M = {}

M.velocities = {}

--To change a value, call M.modifyvelocity(go.get_id(), velocity_variable)
function M.modifyvelocity(id, value)

	M.velocities[id] = value

end

return M

You’ll need to handle the case where you request a velocity before it has been set for a particular game object (if that’s a possible occurrence). You will probably also want to remove the entry if the game objects can be deleted.

4 Likes

That makes a lot more sense.
Thanks!