Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Is this correct use of require() and ModuleScripts?

This is merely an example, asking if this is even right. I see the wiki one but am wondering if this works. Also, I'm currently on mobile. No, this isn't productive. It's an EXAMPLE.

-- module script published, named mainmodule

print("clicked")

return -- ???

-- script

script.Parent.MouseButton1Click:connect(function()
require(mainmodule)
end

If this isn't correct, is this?

-- module script published, named mainmodule

script.Parent.MouseButton1Click:connect(function()
print("hai")
end

return

--script
require(mainmodule)

1 answer

Not quite.

A module script only runs once. That means the first example will more or less work, but it will only print the first time you click.

The second probably isn't right either, since a well designed module should be reusable -- there isn't a reason to use script.Parent, usually, in a module.


The key thing about a module script is that it returns something. In your examples, you weren't using the return to actually give back a value ( a return at the end is already implied -- there's no gain by writing a bare return yourself)

Since a module only runs once, you have to return something that can be used many times.

Usually, that will be a function (or a collection of functions in a table).

For example,

-- ModuleScript
function speak()
	print("Hello!")
end

return speak

We can get whatever was returned by using require in another script:

speak = require(game.ServerScriptService.ModuleScript)

speak() -- Hello!
speak() -- Hello!

script.Parent.Touched:connect(function(hit)
	speak() -- Hello!
end

The Wiki has several full examples here

3 comments

0

Is there any solution to make it run more than once on demand, by clicking it?I need a way to protect my script, or maybe I just did not understand your last paragraph or two. I would appreciate it if you could rephrase.

0

It runs 'on demand'by calling the returned function. For instance, the last example will 'speak' each time the part is touched

0

What is the point of line 3 & 4?

This discussion is preserved as it was. New answers, comments, and votes are closed.