Repository navigation
Expand file tree
/
Copy pathThread System
More file actions
103 lines (79 loc) · 1.87 KB
/
Copy pathThread System
File metadata and controls
103 lines (79 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
local RunService = game:GetService("RunService")
local Threads = {}
Threads._tasks = {}
local function handler(err)
warn(debug.traceback(err, 2))
return err
end
local function stopTask(taskData)
if not taskData then return end
taskData.running = false
if taskData.connection then
taskData.connection:Disconnect()
taskData.connection = nil
end
taskData.thread = nil
end
function Threads:IsRunning(name)
local t = self._tasks[name]
return t and t.running == true
end
function Threads:StartLoop(name, callback, waitTime)
if self:IsRunning(name) then return false end
local taskData = { running = true }
self._tasks[name] = taskData
taskData.thread = task.spawn(function()
while taskData.running do
local ok, err = xpcall(callback, handler)
if not ok then
error(err)
end
if not taskData.running then
break
end
if waitTime then
task.wait(waitTime)
else
task.wait()
end
end
end)
return true
end
function Threads:StartHeartbeat(name, callback)
if self:IsRunning(name) then return false end
local taskData = { running = true }
self._tasks[name] = taskData
taskData.connection = RunService.Heartbeat:Connect(function(dt)
if not taskData.running then return end
pcall(callback, dt)
end)
return true
end
function Threads:RunOnce(name, callback)
local existing = self._tasks[name]
if existing then
stopTask(existing)
self._tasks[name] = nil
end
local taskData = { running = true }
self._tasks[name] = taskData
taskData.thread = task.spawn(function()
pcall(callback)
taskData.running = false
Threads._tasks[name] = nil
end)
end
function Threads:Stop(name)
local taskData = self._tasks[name]
if not taskData then return end
stopTask(taskData)
self._tasks[name] = nil
end
function Threads:StopAll()
for name, taskData in pairs(self._tasks) do
stopTask(taskData)
self._tasks[name] = nil
end
end
return Threads