Okay so I wan't to use module scripts as I can keep my functions manageable. I have two questions,
First Question : Can I use multiple functions in a module script? Second Question : How can I access Functions Inside Module Scripts?
I don't know if im supposed to use _M. before each function or if roblox makes it global for you. I also saw some people doing this:
1 | local myModule = require(game.Workspace.MyModule) |
2 |
3 | myModule.MyFunction(mainArg, secondArg) -- My Function is inside myModule. |
So will this work? And do I need to type _M. Before every module function, and can I change arguments and It'll still work inside the module?
Interestingly someone just asked me this on a twitch stream. I have a funny feeling this isn't coincidence :p
There are two things you need for a module to work.
A ModuleScript somewhere in the game
A script that Requires the module.
The ModuleScript:
01 | local Module = { } |
02 |
03 | Module.SomeFunction = function (parameters) |
04 | -- code |
05 | end |
06 |
07 | Module.AnotherFunction = function (moreparameters) |
08 | -- code |
09 | end |
10 |
11 | return Module |
In a Server Script...
1 | local module = require(game.ServerScriptService.Module) |
2 |
3 | module.SomeFunction(parametertopass) |
4 |
5 | end |
A more practical example:
1 | local AddModule = { } |
2 |
3 | AddModule.Add = function (a,b) |
4 | return a+b |
5 | end |
6 |
7 | return AddModule |
Server Script:
1 | local add = require(game.ServerScriptService.AddModule) |
2 |
3 | print (add.Add( 2 , 3 )) -- will print 5. |
Note that modules will cache, so print(add.Add(2,3)) will print 5, and all subsequent calls will also return 5. (print(add.Add(10000,10000) will print 5 etc etc)
I hope my explanation helped. The wiki page is also very useful
http://wiki.roblox.com/index.php?title=API:Class/ModuleScript