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

Can variables be passed with module scripts?

Asked by 3 years ago

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?

0
I don't really understand. You did not assign a value to the variables inside the module, thus returning nil. What is your goal here? Neatwyy 123 — 3y

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

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:

  • As mentioned above, just use module.num or module:GetNum()
  • Have inc return the new value (the code might look like num = inc(num))
Ad

Answer this question