How does a modulescript work?

So, do you know this instance called modulescripts? It’s very useful to development but it’s not as magical as you think, this tutorial is not about how to use them but how they work.

So a quick start, when you create a modulescript and open it this should appear.

local module = {}

return module

yeah. Now at most module scripts(well, all) you will see something like this

local module = {}

function module.Print(string)
print(string)
end

return module

What does this module.print do? Your just assigning a function to the module table. Proof? Here.

local module = {
Print = function(string)
print(string)
end
}
return module

And yes it works the same way, but why do we do function module.yourfunction instead? Because it’s much cleaner and you can replace the dot with : unlike the proof method.
Which can return self.

Now, what does require do, really? When you call require on a modulescript it just returns a table from the module script. Simple right?

This is also the same with variables, you can also try it in a normal script

Before this ends, after I heard all of this, are modulescripts still useful?

The answer is yes. Because you can reuse functions so you’d don’t have to rewrite them.

In short, require just returns the table from the modulescript which contains functions and variables

Well, I hope you learned something.

also ik it’s extremely short but there’s really nothing else to say about them

3 Likes

ModuleScripts don’t have to return tables, for anyone wondering.

--ModuleScript
return function(A)
    print(A + 2)
end

--Script
local PrintPlus2 = require(<MODULESCRIPT PATH>)

PrintPlus2(2) --prints 4
PrintPlus2(0) --prints 2

They can return anything except for nil check edit below for details

Edit

ModuleScripts CAN return nil, but only explicitly

return nil

in a module causes no errors, while

return

or simply having no return at all causes
module return no

--ModuleScript
return false

--Script
print(require(<MODULESCRIPT PATH>)) --prints false
1 Like

yeah , im just saying in general not actually

i forgot to include that

I’ve made a couple of ModuleScripts return nil with no issue:

--ModuleScript
export type MyType = {
    Key: any
}

return nil

--Script
local module = require(ModuleScript)
local data : module.MyType = { Key = "value" }

It may have been the fact that I exported a type however.

1 Like

After testing a bit, I found you ARE allowed to return nil specifically, but you can’t have no return statement, OR an empty return (aka a return statement with nothing after). I made an edit to my original reply.

1 Like