The title says it all. I am trying to shorten some really repetitive functions and export them to a module script. However, I've found that I can further shorten my code if I can also pass at least 2 variables with the module script as well.
local module = {Letters, OrderedLetters} return module
(I cut out the other functions that are in the module script)
local Module = require(parentModel.ModuleScript) local Letters = Module.Letters local OrderedLetters = Module.OrderedLetters
Yet for some reason, I continue to get an error that the imported variables are nil. Have I completely misused module scripts?
local module = {Letters, OrderedLetters}
creates a list where the first item is whatever Letters
refers to and the second item is whatever OrderedLetters
refers to. The way you are trying to use it, you want to do this instead:
local module = { Letters = Letters, OrderedLetters = OrderedLetters, }
Note that "variables" cannot be passed or shared with module scripts, only values. This distinction is important. Here's an illustration:
-- ModuleScript local module = {num = 1} function module:Inc() self.num += 1 end return module -- Calling script local module = require(script.Module) local var = module.num print("start:", var, module.num) -- 1, 1 module:Inc() print("after Inc:", var, module.num) -- 1, 2 var = 5 print("after var = 5:", var, module.num) -- 5, 2
The point is that the num
variable is not shared, only the value referenced by num
. This normally shouldn't be a problem: you can just access module.num
to get the latest value. In the event you have some code where you need to effectively share a "variable", you can sort of accomplish this by wrapping it in a table (but this means that all the code has to expect that it'll be dealing with a table containing the desired value rather than the value itself). For example:
-- Before: local function inc(v) v += 1 end local num = 1 inc(num) print(num) -- 1 -- but if we want this to be 2, we can rewrite all this as... -- After: local function inc(v) v[1] += 1 end local num = {1} inc(num) print(num[1]) -- 2
Superior alternatives that will work most of the time:
module.num
or module:GetNum()
inc
return the new value (the code might look like num = inc(num)
)