Will this variable get garbage collected?

Simple question but I’m unsure; will this get garbage collected?

local ReplicatedStorageService = game:GetService("ReplicatedStorage")

local Test = require(ReplicatedStorageService:WaitForChild("util"):WaitForChild("Test"))
local Dummy = require(ReplicatedStorageService:WaitForChild("util"):WaitForChild("Dummy"))

I have a startup script that currently doesn’t do anything except require other modules. After the local Dummy variable the script ends so my question is, will it get gc’d? Or does it stay in memory until the module is deleted?

It doesn’t matter whether it gets garbage collected or not, either way it will be loaded zero or one times, depending on if anything calles require() on it. If it is possible for another script to require the same module and observe something a previous script changed, then the module must assume it is always accessible and thus cannot be garbage collected. If it is not possible to share information through a module script this way, then the game can safely assume that anything in the module has the same or shorter lifetime than the call to require(), in which case it will be garbage collected. I don’t remember which way it is, but thats both possibilities based on what must be the case for modules to work correctly in general. tl;dr don’t worry about it too much.

A script will stay in memory even if execution ends (proof of this is that they remain in the workspace). Scripts can be restarted by toggling their Enabed property. A script is destroyed when either it, or an ancestor, is destroyed via instance:Destroy(). A script will be GC’d if it, or its ancestor, has its Parent set to nil and no other Lua variables hold a reference to it.

ModuleScripts are singletons, meaning a single instance is created and shared among all scripts that require it in the same execution context. Execution contexts are Local, Server, and Actor, so a Local script that requires a ModuleScript will get a different instance of it then a Server script will, but it will get the same instance that another Local script would get.

1 Like