What are some scripting practices/things I should know? I'm working on shifting from regular scripts to OOP/Module script based coding

Hello!
I’m working on transitioning over to module scripts since regular scripts are no longer suiting what I want to make. I’ve already got a bit of knowledge on OOP, plus the general basis on how module scripts work. The only real thing I’m actually stuck on is:

  1. What kind of structure/way should Module Scripts be set up?
  2. How should I separate code into Module Scripts?
  3. What are some good general practices for them?
    My friend did show me his style of a Module Script base:
local Module = {}

function Module.init()
end
function Module.update(dt)
end
return Module

but I have yet a need for it in anything, nor do I know how to use it properly yet.
Thank you in advance!

First I’d say it’s the general setup with .new() constructor to interact with separate objects:

local module = {}
module.__index = module

function module.new()
    local self = {}
    self.SomeProperty = "Test"

    return setmetatable(self, module)
end

function module:GetProperty(index: string)
    if self[index]
        return self[index]
    end
end

return module
local Module = require(path.to.module)

local New = Module.new()
print(New:GetProperty("SomeProperty")) -- "Test"

That’s it for the basic object-based structure.

If you want to add a method that will execute certain code when you run the module for the first time, you can do:

  1. Just keep the code in the module’s body, it will execute only once on the first require, as modules cache
local module = {}
module.__index = module

function module.new()
    local self = {}
    self.SomeProperty = "Test"

    return setmetatable(self, module)
end

function module:GetProperty(index: string)
    if self[index]
        return self[index]
    end
end

-- example
module.PartCache = {}
for _, Part in workspace.Parts:GetChildren()
    table.insert(module.PartCache)
end
--

return module
  1. You can make a method like :start() or .init(), but I personally prefert start()
local module = {}
module.__index = module

function module.new()
    local self = {}
    self.SomeProperty = "Test"

    return setmetatable(self, module)
end

function module:GetProperty(index: string)
    if self[index]
        return self[index]
    end
end

-- example
function module:start()
    module.PartCache = {}

    for _, Part in workspace.Parts:GetChildren()
        table.insert(module.PartCache, Part)
    end
end
--

return module

So whenever you initialize the module, you can call the method.

local Module = require(path.to.module)
Module:start() -- we initialize the module after requiring it
-- this way we can also call this method multiple times (if needed and applicable)

One more major approach would be making and using base classes:
Baseclass code:

local BaseClass = {}

function BaseClass:Attack()
    -- perform attack code
    print("Attack")
end

function BaseClass:Dodge()
    -- perform dodge code
    print("Dodge")
end

return BaseClass 

Derived class code:

local Warrior = setmetatable({}, {__index = require(path.to.BaseClass)})

-- by defining a method that has the same name as a method from base class,
-- we are overriding it
function Warrior:Attack()
    -- perform attack code
    print("Overridden attack")
end

return Warrior

Now an example

local WarriorClass = require(path.to.Warrior)
WarriorClass:Attack() -- "Overridden attack"
WarriorClass:Dodge() -- "Dodge"

Our :Attack method inside Warrior class has overridden the method from base class, but as we didn’t specify a dodge method - it inherited the method from the base class.

EDIT: Hopefully there’s not going to be any typos, written all the code thru forum post editor

Thanks for some explanation. Definitely going to be trying out some module stuff during the next few days.
As a side note, do you know if there’s any way to make fast raycasts? As in, being able to make tens or at the maximum, hundreds of raycasts a second/half a second? I’m thinking of making a realistic reactor simulation.

Raycast itself is really fast, and cannot really go faster as it is a native feature. You’ll just need to finetune the RaycastParams for it to only query with the instances you need.

Good, now never use it again and switch to ECS

metatable OOP is really bad the way people use it tbh
Use alternative OOP approaches or learn ECS which is even easier than OOP to some degree and does not have bloated runtime deoptimizations

Or people just should write the way they are comfortable doing so. It’s their projects and their comfort zone.

People shouldn’t just follow everyone’s advices blindly and try to follow approaches that might not suit their programming style or/and use case.

I’ve seen it often how people were trying to overuse practices that weren’t applicable for what they were doing just because they thought that it’s the “right” way of doing things.

ECS is a very good approach for handling entities and easily modifying their behavior, and that’s why it exists. It’s not meant to REPLACE OOP.

Reading a “holy manuscript of how to code right” always was one of the biggest issues why people’s projects were getting stuck in infinite development limbo. Infinite micro-optimization never done anyone a good favor.

Yeah, I ended up figuring that out after my neutron simulation was able to run hundreds every RunService heartbeat.

Honestly if I ever use a tutorial for anything, it always feels.. off. Like the code doesn’t exactly match with the rest. Also, what even is ECS?

Disagree.
There is no “my opinion” in programming
There are only efficient and inefficient methods. :handshake:

Just putting in my 2c and echoing what @VioletElementalist mentioned; don’t get TOO caught up in what’s ‘the best way to write something’. Since there’s no native way to produce classes in Luau, there’s different flavours of doing Roblox OOP that differing programmers will swear by and recommend. Different strokes for different folks.

With what Yarik is saying, some approaches are technically more efficient than others, but as long as your code functions reasonably well and produces the gameplay you want then it serves its function :slight_smile: take toby fox’s coding for undertale as an extreme example.


Anyhoo, I strongly recommend you look into Maid modules. The most popular one is Quenty’s, which is what myself and other successful developers use. This is a module object that you should ideally create and link to each of your custom classes when you call .new(). It’s a helper object that makes unlinking data from your custom object easy and convenient when you need to delete it.

How I use the maid module:
image

It’s important that you properly unlink data when destroying a custom object or you will end up with redundant floating data in your game’s memory (a data leak). Unfortunately this is hard to track as custom objects aren’t visible in the explorer tab, however you’ll know something’s wrong if the Memory stat tracks up worryingly high or if your frames drop.

ECS is entity component system.
You use hashmaps and “systems” (usually switch tables)

local Plr:Player = game:GetService("Players").LocalPlayer
type Entity = {Rank:number;XP:number}

local EntityList:{[Player]:Entity} = {
	[Plr] = {Rank=0;XP=0;}
}

local switch:{[string]:(Plr:Player,...any)->(...any)} = {
	LvlUp = function(Plr:Player,Lvl:number)
		EntityList[Plr].Rank += Lvl
	end;

	_default = function(Plr:Player) end
}

local function System(Plr:Player,Ability:string,...:any):...any
	return (switch[Ability] or switch._default)(...)
end

--Rank up
System(Plr,"LvlUp",1)

That’s a wrong display of ECS approach, ECS is not just “usually a switch table”.
This article should cover it: All about Entity Component System

That a Luau adapted ECS approach
There is different ways to implement ECS but switch table is the most scalable in my opinion.
After all “S” in ECS stands for system so its up to your own implementation.

There is a conventional idea how ECS works. ECS is not a switch table. If we are talking about “efficient” and “inefficient” - this isn’t either scalable or correct from the point of ECS approach.

I’d suggest making research on the topic before telling people all around DevForum “Use system X instead of system Y”, especially if you are showing a fundamentally wrong example that doesn’t correlate with the convention of the system you tried to “put on the throne”, as it’s misleading people into adapting wrong patterns.

Entity → ID
Component → data container
System → logic (usually a loop)

Your previous example is not ECS, There’s no iteration or batch processing in your code, it’s just a command call.
What you have there is just a procedural program, nothing more.

OOP, ECS, MVC are all design patterns and these are all theoretical concepts, too much theory doesn’t convert very well to their actual practical and applicable use! Like from the example we see from your code, it just seems that you knew the surface level theory; or understand the theory but fail to implement it practically. The true answer to this question is whatever you feel is easy, intuitive and does not demotivate you to continue your game. An idiot admires complexity but a genius admires simplicity!!

You can’t just say a bunch of buzzwords and claim that I am wrong without full elaboration.
I have explained it in a way that so anyone who is not aware of ECS could understand and this escalation from you into passive agression is at best rude.

Even if I was wrong, 2 wrongs don’t make a right.
Because now you are the one who is blatantly wrong with this nonsensical claim.

ECS is a pattern. Not a license. Not a doctrine.
What I shared is a minimal ECS - simple and idiomatic for Luau.

it isn’t ECS to begin with, let alone be minimal

I think you should learn about the pros and cons of OOP and ECS as well as how best to combine them since they are not incompatible. I would suggest reading this article if you want to learn more: MVC: A Practical Approach Towards Developing Games