I have a problem. I fire a module script function from an another script. How can i get thread in that function to close it inside the function.
I found a hacky solution using getenv
and setenv
:
Script:
local foo = require(script.ModuleScript)
local env = getfenv()
env["thread"] = task.spawn(foo.bar)
setfenv(1, env)
ModuleScript:
local foo = {}
function foo.bar()
--the function must yield for a frame else it won't work
task.wait()
local thread = getfenv(0)["thread"]
print(thread)
end
return foo
Edit: Upon further inspection, I noticed that if you try to cancel the thread within the module function, the error cannot cancel thread
occurs, this is the first time I have encountered this error and I haven’t figured out how to fix it.
Edit 2: The error is caused every time a thread tries to cancel itself, in this case, a module function tries to cancel the thread running it. It can be manually caused if you run task.cancel(coroutine.running())
Another option is using coroutine.running
, although this also doesn’t work for task.spawn
(only for the current script environment):
Script:
local foo = require(script.ModuleScript)
foo.bar()
ModuleScript:
local foo = {}
function foo.bar()
local thread = coroutine.running()
print(thread)
end
return foo
If you want to the script running the module function, just do getfenv(0)["script"]
:
Script:
local foo = require(script.ModuleScript)
foo.bar()
ModuleScript:
local foo = {}
function foo.bar()
local scr = getfenv(0)["script"]
print(scr)
end
return foo
Did you set the thread
variable of env
as shown in the script?
yes i did
No, I mean on the script that calls the function:
local env = getfenv()
env["thread"] = task.spawn(foo.bar)
setfenv(1, env)
Also in your module, you must wait for a frame using task.wait
before setting the thread
variable.
can you respond pls? it still doesnt work