ModuleScript code running in the ModuleScript?

I tried to use a ModuleScript as I will be using a function many times and I will be upgrading it soon, here is the ModuleScript code:

local Despawn = {}
Despawn.Despawn = function()
wait(30)
script.Parent:Destroy()
end
return Despawn

And here is the script code:

local DespawnModule = require(game.ServerScriptService.Despawn)
DespawnModule.Despawn()

Now the error I get in the explorer is this:
The Parent property of ServerScriptService is locked
Which means the script is running inside the ModuleScript??

You’re trying to destroy ServerScriptService, What are u trying to do?

I am trying to destroy the Parent of the script that’s using require

Then put the module script as a parent to the requiring script…

That doesn’t solve the issue of tyring to minimize the amount of scripts i’ll be using. Isn’t that the whole point of a ModuleScript?

Try this instead:

-- ModuleScript (inside of ServerStorage)

local Despawn = {}

function Despawn:Despawn(object)
    object:Destroy()
end

return Despawn
-- ServerScript (inside of an object)

local Despawn = require(game.ServerStorage.Despawn)
Despawn:Despawn(script.Parent)

This works just as I want it to, but I don’t understand what’s going on, could you please link me something to understand what you done here? Or better yet explain it to me please?

The script in your ModuleScript refers to the ModuleScript. Your module essentially exports a function that will wait 30 seconds and destroy the ModuleScript, regardless of what called it. There is also nothing that can tell the function what to destroy other than the ModuleScript.
You were confused because you thought that a ModuleScript would act exactly as if the code were copied to where you required it. It doesn’t work that way.

@P1X3L_K1NG’s code adds a parameter to the function, object, which is the object to destroy. Now the function can be told what to destroy, which is the current script’s Parent.

Your original code could be improved with getfenv(2), which can get the globals of the script that’s calling the function. From there, you could get the script of the script that’s using the function, and then delete that script’s parent - solely with code from the ModuleScript, and without having to pass the current script.

2 Likes