Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

[SOLVED] How to run a function once in Object-Oriented Programming?

Asked by 2 years ago
Edited 2 years ago

Hello. I'm trying to make my own Custom Signal module without using BindableEvents nor using a module from the DevForum. But I don't know how to make the handler Signal:Once() which basically uses Connect but only does it once. I tried using coroutines, debounce, and setting the function to nil, but it still runs more than once like Signal:Connect() and not like RBXScriptSignal:Once(). Here's the module for reference:

01local module = {}
02module.__index = module
03 
04local backupBindableEvent = Instance.new("BindableEvent")
05 
06function module.new(signalName: string)
07    local self = setmetatable({}, module)
08    local newSignal = {}
09 
10    local newSignalName: string
11 
12    if signalName ~= nil then
13        newSignalName = signalName
14    else
15        newSignalName = "Event"
View all 79 lines...

Also I don't know how to make the Signal:Wait() function. Right now, I'm temporarily using BindableEvents to make those functions work.

And also, if you noticed anything wrong in my module that is off-topic, lemme know!

0
Wait will be almost the same as :Once but at the end instead of returning, do a repeat wait() until not myTable.Connected blowup999 659 — 2y

1 answer

Log in to vote
0
Answered by
blowup999 659 Moderation Voter
2 years ago

It's hard to help here because this is highly dependent on the listenersModule you have - Personally, I would add an :AddOnce(func) in addition to :AddListener(func) and let that module handle it, but this also runs into the issue of the Connected variable being different from reality.

Easiest way with given code is:

01function newSignal:Once(func)
02    local myTable = {Connected = true}
03    local function singleUse()
04        myTable:Disconnect()
05        func()
06    end
07    listenersModule:AddListener(singleUse)
08    function myTable:Disconnect()
09        listenersModule:RemoveListener(singleUse)
10        myTable.Connected = false
11    end
12    return myTable
13end
0
The listenersModule has 3 functions: :AddListener(), :RemoveListener(), and :GetListenersAsync(). The listenersModule just simply creates an array of functions T3_MasterGamer 2189 — 2y
0
I also need help in making the :Wait() function. Thanks! T3_MasterGamer 2189 — 2y
0
But sure, I’ll try to make an :AddOnce() function. T3_MasterGamer 2189 — 2y
0
Sadly, yours did not work but I finally solved the :Once() function. I just converted the listener to a thread, and closed it once it was fired to avoid of doing it again. T3_MasterGamer 2189 — 2y
Ad

Answer this question