[OOP] coroutine module help:
- What do I want to achieve?
A: I need someway to run a loop within a coroutine, which yields for a set parameter of seconds and can be stopped by changing a ‘active’ variable. The ‘active’ variable will be changed via a class method thread:Run()
, thread:Stop()
.
- What is the issue?
A: I can’t figure out how to make this work, I debated using: coroutine.wrap(self.func)(...)
within a while wait() do to run a function continuously at the same time using a coroutine.
“What would be the most efficient way to do this with coroutines?”
I have created some starter OOP code in a ‘thread’ class here:
local thread = {}
thread.__index = thread
thread.tasks = {}
local coroutine = coroutine
-- Code:
function thread.new(foo, i) --> thread:
local self = setmetatable({}, thread)
self.func = foo
self.interval = i or 0.5;
self.active = true
self.Thread = function(...)
if self.func then
-- (Somehow) with coroutine
-- Create thread here with interval of self.interval
-- Possibly coroutine.yeild? task.wait() or wait()?
end
end
function self:Run()
self.active = true
return self
end
function self:Stop()
self.active = false
return self
end
return self
end
return thread
thanks,
2 Likes
Man first of all that OOP thing sounds like POOP or POO backwards, Anyways im not very experienced with this whole coroutine thing but from what I can see you are trying to make your module put to sleep a thread and make it so if that variable thing changes it unyields it right? May I ask what are you using this module for?
I would use RunService.Heartbeat
and keep track of the elapsed time to create an interval, which you can just :Disconnect
at any time to stop it, and its also accurate as it gives you the delta time.
An example:
local t = 0 -- the elapsed time
local connection = RunService.Heartbeat:Connect(function(dt)
-- increase the `t` variable by dt
-- which is the seconds elapsed since
-- the last Heartbeat
t += dt
if t < 5 then
return -- stop the function if 5 seconds haven't elapsed yet
end
t = 0 -- reset the timer
print("hi")
end)
-- to stop it
connection:Disconnect()
If you want to do this within a loop instead, just pass a condition to your while loop
while active do
task.wait(5)
end
1 Like
OOP stands for object oriented programming or a class based over a procedural one. Similar to a language like java, but for lua’s case we use something called ‘metatables’
example: Dog.new() → creates a new dog object
In this case, Thread.new() → needs to create a ‘thread’ object thats created by coroutine.wrap or coroutine.create.
I want my thread object to operate like this, somehow theres a loop within a coroutine wrap that automaticly kills the thread if I change my active variable.
I’m using this module to thread a ‘behavior’ function. This will control a NPCS pathfinding and logical behavior. I’m using a ‘thread’ or coroutine because these npcs will need to be executing the function at the same time. I’m trying to avoid using spawn(). thanks