Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to share variables through require?

Asked by 6 years ago

So I'm making private modules, but I am not sure how to share variables.

I have tried _G but that does not seem to work

I have also tried doing

require((29185912) (Product_ID)

Also once I do it, how would I transfer it the module script and use it?

1 answer

Log in to vote
0
Answered by 6 years ago

We use what is called accessors and mutators ie get data (read only) set data (validate then set copy) this is the basics of OOP.

An example would be :-

local vars = {}
local f = {}
local get = {}
local set = {} 

-- add variables
vars.a = true

-- return a variable
function get.getA()
    return vars.a
end

-- set variable a
function set.setA(val)
    if typeof(val) == 'boolean' then
        vars.a = val
    end
end

function f.printA()
    print('a is', vars.a)
end

return {get = get, set = set, f = f} -- return our functions 

Script:-

-- for quicker access make variables to point to our tables
local module = require(script.Parent.ModuleScript) -- unpack our table into its components
local get, set, f = module.get, module.set, module.f

print(get.getA())
f.printA()

set.setA('Hi') 
f.printA()
set.setA(false) 
f.printA()
print(get.getA())

Working with private modules can be difficult as allowing the user to input data can leave it vunrable so you should test for this.

I hope this helps

Ad

Answer this question