Different variables every time module script is ran

So i need variables not to overlap when module script is ran more than once from different scripts.
Lets say i have some code here

module = {}
local number = 1
local function add()
   number += 1

function module.start()
   (calls add when remote event detected)
end

return  module

Yeah so how do i stop numbers from overlapping. this isnt my actual code it just a demonstartion

1 Like

The number variable is a global variable that is used for this specific module, that means that every changes from any script will be for this specific variable. To fix this you will have to use metatable that would be the the module, and for each script using the module add a function that creates a table setting the metatable to be the module table which contains the number variable. That would look something like this:

module = {}
module.__index = module -- used to create separate tables all sharing the same properties
local number = 1

function module.new()
    local self = setmetatable({}, module)
    self.number = 1
    return self
end

function module:add()
   self.number += 1

...

return  module

From each script you will have to create a table using the new function and only then start using functions from the module:

local module = require(modulepath)
local numberCounter = module.new()

numberCounter:add()
1 Like

what about the remote events things, or would
it be the same. also what do you mean by meta tables

Depends on what do you want to do with the remote events, if you want to start counting when the remote event is fired you just need to change module.start() to module:start().
Regarding the metatables, they are tables that helps a different table be more flexible, in this case, the setmetatable() method basically means that the module table will be a “blueprint” for a table, with each script using the blueprint to create its own table.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.