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

What does require mean? Why do we use it? Why is it useful?

Hello! I see this all the time, and I've tried to look almost everywhere online for this, but I can't find it anywhere. The question I have is what does require mean in scripting? Why do we use it? Why is it useful? I want to know?

If you can help me, Thank you so much then!

2 answers

They generally are used for ModuleScripts. For example:

--This is a module script

local banned = {
	["LazerShatters"] = true
}
return banned
--This is a server script
local modulescript = require(game.ServerScriptService.ModuleScript) --Get the modulescript

game.Players.PlayerAdded:Connect(function(player)
	if player.Name == modulescript then
		player:Kick("Banned.")
	end
end)

Modulescripts are usually used as a global script, to be accesssible by other scripts. To grab the module script's table you'd need to set a require function to a variable to access the module script's table.

3 comments

0

So you mean like that require gets the module script that in the Serverscriptservice?

0

A Module script can hold functions that local script and sever scripts can access by require(modulescript), example

0

As FirezDevv said, Modulescript can hold information accessible by the server and client.

Before you understand require you need to understand ModuleScripts.

ModuleScripts are generally used to write reusable libraries of code that you can use across scripts. Instead of duplicating the same code across scripts, you can instead have it in one place, i.e. a module. Then all the scripts that need the same library can just require it.

There are two ways to require a ModuleScript.

First one, is by getting a reference to the actual ModuleScript instance.

-- ReplicatedStorage.math_ext.luau

local math_ext = { }

function math_ext.secant(n)
    return 1/math.cos(n)
end

function math_ext.factorial(n)
    return n == 0 and 1 or n*math_ext.factorial(n - 1)
end

return math_ext

Then you would require it in a different script:

-- ServerScriptService.Script.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local math_ext = require(ReplicatedStorage.math_ext)

print(math_ext.factorial(5)) -- 120

The second way is to require by its asset ID. You need to upload it to Roblox as a free model, but naming the ModuleScript instance "MainModule".

local MainModule = require(123456789)

And it works the same way.

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