Help with OOP and Events

I’m creating a player mouse collider system, where a constructor function is used to create mouse colliders.

My intention is for every collider to listen for player mouse movements/clicks and fire their respective BindableEvents, but i’m forced to place the mouse events in the constructor function which clutters it a lot and makes those events accessible to the requiring script.


How can I better implement the events and make them private?
Am I going about this wrong?

Here’s what I have so far:

--!strict
--services
local UserInputService = game:GetService("UserInputService")

--data types
type point = {x: number, y: number}

--------

local module = {}
module.__index = module



function module.newFromPoints(point1: point, point2: point)
	local self = setmetatable({}, module)

	self.P1 = point1
	self.P2 = point2
	
	--events would go here but i don't want them here!
	
end

return module

Any help is appreciated.

Luau does not support OOP as a whole, so the concept of privatized members isn’t readily available. You could create an up-value in the module’s main scope that maps self to its private data, which the methods of the class form a closure with and have sole access to. This isn’t really necessary though. You could use privatized notation by prefixing the property of self which holds the BindableEvent with an underscore, then expose BindableEvent.Event as a public property:

self._Example = Instance.new("BindableEvent")
self.Example = self._Example.Event

On another note, I do not recommend using BindableEvents for custom RBXScriptSignal implementations. They’re slower compared to engineered alternatives, and also clone their passed arguments. I recommend using LemonSignal instead

You can start a variable name with “_” to remind you that you aren’t supposed to set it directly. You can also override the __index metamethod to add your own access control, but I don’t recommend this. There aren’t any private-style access modifiers.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.