ModuleScripts and "local" variables

I believe the reason the variables are shared is that you are returning the same table address as defined as module {} as you have experimented which was created within the module script.

To solve this you can create a constructor function to initialize a different table to make the variables “local” like in object-oriented programming.

Taking the example of newCar you can do something like this to create the local copy of variables you are looking for.

local module = {}

function module.new()
    --create the new table to avoid referencing the shared table.
    local localModule = {}
--gives the local table the :functions() or .functions() methods
    setmetatable(localModule, module)

    localModule.cache = 1

    return localModule
end

function module:getCache()
      return self.cache
end

function module:setCache(c)
     self.cache = c
end

return module

However, you don’t really need the functions to set and get the cache as the constructor will return a dictionary that can be edited.

--require the above module

local newLocalModule = module.new()

print(newLocalModule.cache)
newLocalModule.cache = 5
print(newLocalModule.cache)

Yeah by convention it’s not a good idea to have one liner functions to return a singular value when you can just directly access the dictionary like above.

3 Likes