I want to instantly kill a thread, basically just disabling a script, but a thread/coroutine instead.
Q&A:
-
Q: What’s the issue?
-
A: I want to instantly kill a thread, by not having to disable a script, nor destroying a script. I can’t disable a script, because I hit some rough problems, I’ll go through this below.
-
Q: Why can’t you destroy and/or disable a script?
-
A: It’s hard to explain, basically I’m doing a script-per-part system, so when an “interactable” part has been placed, a script is put inside the part, so the part becomes “interactable”, the problem is, I’m doing a client sided system too, so localscripts are included, and they only get executed in PlayerGui, PlayerScripts, etc. I would like to see localscripts get executed anywhere in the near future. Say we have a “script” inside the “interactable” part. Once a player deletes a placed “interactable” part, the thread must be killed to clean up mess and useless clutter in memory. The “script” inside the “interactable” part will be destroyed along with the part. This is not easy with localscripts since, once again, local scripts does not execute anywhere, just PlayerGui, PlayerScripts, etc. so then they wont get deleted once the “interactable” part gets destroyed.
If there is a better workaround to this, even without threads/coroutines, please let me know.
I attempted to make a workaround for this, but today was not the day…
local killThreadEvent = Instance.new("BindableEvent", script)
killThreadEvent.Name = "KillThread"
local threads = {}
local function newThread(func)
local thread
thread = coroutine.create(function()
killThreadEvent.OnEvent:Connect(function()
local i = table.find(threads, thread)
if not i then
print("killed")
coroutine.yield()
end
end)
print("created")
func()
print("ended")
end)
table.insert(threads, thread)
return thread
end
local function killThread(thread)
local i = table.find(threads, thread)
if i then
table.remove(threads, i)
killThreadEvent:Fire()
end
end
local thread = newThread(function() print("abcdef") wait(5) print("foo bar") end)
coroutine.resume(thread)
wait(3)
killThread(thread)
I’ve seen other posts about “how to kill a thread”, I know about it, but now I’m just desperate for help.
tl;dr:
Kill threads/coroutines, outside of thread/coroutine, without having to disable script.
-fronthd