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 8 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:

local myModule = require(game.Workspace.MyModule)

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?

1 answer

Log in to vote
2
Answered by 8 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:

local Module = {}

Module.SomeFunction = function(parameters)
    -- code
end

Module.AnotherFunction = function(moreparameters)
    -- code
end

return Module 

In a Server Script...

local module = require(game.ServerScriptService.Module)

module.SomeFunction(parametertopass)

end

A more practical example:

local AddModule = {}

AddModule.Add = function(a,b)
    return a+b
end

return AddModule

Server Script:

local add = require(game.ServerScriptService.AddModule)

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

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