How to Deinitialize modules

I’m sick of modules always getting a ‘cached’ version. When I call a module I want to get all the items from the top as if it’s a brand new script. Main example I use is in GUI’s I use 1 LocalScript, it gets all the modules to each individual UI element (menus, inventory, etc.)

And if I have say a health bar module, it might look something like this

local HealthBarModule = {}

local Frame = script.Parent

Frame.Size = UDim2.new(1, 0, 1, 0)

return HealthBarModule

Now if I die and reload as a new character and the UI resets (ResetOnSpawn set to true, I am NOT setting it to false. It ends up causing more frustration) it means that ‘Frame’ is referring to the old, destroyed UI and not the new Frame. I don’t ever see why this occurs, as to me the original HealthBarModule should be deleted, and this is a completely new module, so it should run the full code.

So how can I deintiliaze all the modules easily. I don’t wanna have to go into every single one and check for player death inside them

This functionality doesn’t exist in Roblox, but there are two workarounds for your situation:

  1. Clone the ModuleScript to ensure it isn’t cached (note: script will be nil unless you set the Parent).
  2. Change your ModuleScript to return a constructor function for your object rather than relying on returning the object.
return function()
	local HealthBarModule = {}

	local Frame = script.Parent

	Frame.Size = UDim2.new(1, 0, 1, 0)

	return HealthBarModule
end
local MyHealthBar = require(script:WaitForChild("HealthBarModule"))()

Of those two options, you should go with the second one since it isn’t a workaround for ModuleScript caching and using constructors for objects is the standard for object-oriented languages, including Lua with metamethods.

6 Likes