Using Actors and ModuleScripts to facilitate DRY and quick iteration!

While creating my implementation of complex vehicles with tire pressure physics and server-client control tradeoff, I found it hard to create scripts that shared functionality across the client-server boundary. At first, my solution was to use a ModuleScript with a server and client script each calling require on it. This worked as a simple method to share functionality over client and server scripts, and I could use RunService’s :IsServer or :IsClient methods within the module to differentiate between contexts that the script was running from, but it left something to be desired. I wanted a nice and simple way to call modules, and I wanted to store the modules outside of my vehicle models so that I wasn’t relying on every vehicle containing a copy of the same module. This is where actors helped quite a bit! There’s a niche detail that’s not covered within Roblox’s multitreading or Actor documentation. That functionality is the creation of a new Lua environment when require is called on a module for the first time within an Actor! This means that you can place client and server scripts all across the data model, and as long as they’re placed in an actor, each time they require a module, they’ll do so within a new environment. You can even determine where the module is being run from through the use of the script:GetActor method within a module, which will return the actor that the script which requires the module is running from. This means that modules can be extended to have multiple run contexts with only one ModuleScript instance!

Anyhoo, I hope someone got something out of this since I wasn’t able to find much information about this feature, and it makes scripting with ModuleScripts much faster and (I think) simpler! Thanks for reading! <3

7 Likes

That is an interesting way to use actors,

However, I don’t think this is the right category for this post, it should probably go in #resources:community-tutorials

1 Like

Oh sorry. I thought it made more sense a a resource. I’ll move it.

1 Like