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

Is this correct use of require() and ModuleScripts?

Asked by
unmiss 337 Moderation Voter
9 years ago

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

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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

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. unmiss 337 — 9y
0
It runs 'on demand'by calling the returned function. For instance, the last example will 'speak' each time the part is touched BlueTaslem 18071 — 9y
0
What is the point of line 3 & 4? unmiss 337 — 9y
Ad

Answer this question