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

How do you access functions in module scripts?

Asked by 9 years ago

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:

1local myModule = require(game.Workspace.MyModule)
2 
3myModule.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?

1 answer

Log in to vote
2
Answered by 9 years ago

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:

01local Module = {}
02 
03Module.SomeFunction = function(parameters)
04    -- code
05end
06 
07Module.AnotherFunction = function(moreparameters)
08    -- code
09end
10 
11return Module

In a Server Script...

1local module = require(game.ServerScriptService.Module)
2 
3module.SomeFunction(parametertopass)
4 
5end

A more practical example:

1local AddModule = {}
2 
3AddModule.Add = function(a,b)
4    return a+b
5end
6 
7return AddModule

Server Script:

1local add = require(game.ServerScriptService.AddModule)
2 
3print(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

1
Sorry to revive an old post, but I'm trying to figure some stuff out here. One thing is, if a module function will only ever return the same result, then what's the point? I'm trying to use a ModuleScript to run combat functions between various weapons and targets, but if the results don't change I should just code it into each local script. TerminusEstKuldin 40 — 6y
Ad

Answer this question