How do I make a module a singleton?

Let’s say I have a module that I want to act as a service called InventoryService.
Now, in the module, I would be caching inventories via playerAdded and playerRemoving (running code outside the module’s table).

I would have some functions, like InventoryService:CreateInventory(player)

My question is, when I require this module, how do I make it a singleton, so that if I required the module in more than one script, the code inside of it wouldn’t run twice even though it’s required in both scripts?

This is so that if I required it in any script, they would all be referring to one single area, and not the code that’s running inside of the script that was required.

Ex.

InventoryService module creates inventories on playerAdded/Removing and handles that internally. If it’s required anywhere else, it will just be pointing to this one “hub” where everything is being handled instead of re-running its code in the script it was required in. If I was able to accomplish this, I could require InventoryService in any script and use something like InventoryService:Get(player) or InventoryService:ClearInventory(player) in any script, but it would all be getting info, performing actions, etc. in the same place (the scope of the module should be outside of any script it’s required in is basically what I’m saying).

Only way I can think of to do this is to maybe have another script inside the module, and have the modules get the info from that script via Bindables, but I’m not sure how efficient this is, and I want to see if there are any other options. This is going to help me create a framework of some sort.

Modules scripts are lazy loaded, so the code inside of it will only run once.

Oh, really?? I didn’t know that.

So basically if I did some playerAdded/Removing stuff and cached inventories in a module, if I required the module in multiple scripts and then called methods inside of the module’s returned table that referred to the inventory cache outside of the table in the scripts, the scripts would all be referring to the same place? And the connections outside of the table in the module are ran only once?

Yes they would all be referring to the same place.

1 Like

Perrrfect. Thanks so much, needed clarification

1 Like