I’m trying to make a function with a wait()
statement except I want to keep the rest of the code running normally, how do I do that?
This:
task.spawn(function()
-- run your stuff here
end)
-- rest of the code
Or this:
local function toSpawn(arg1, arg2)
-- code here
end
task.spawn(toSpawn, arg1, arg2)
-- rest of the code
Your code will run in a different thread and thus not slow down the rest of the code, useful in a while loop or with excessive waits.
Edit: thanks to @Ziffixture for improving the code here
I want to run a function from a moduleScript, is there a way to do that?
I would think this:
local module = require(game.ReplicatedStorage.ModuleScript) -- change path
task.spawn(module) -- if the module returns a function
task.spawn(module.function) -- if the module returns a table, change function name!
or, if you need to pass arguments:
local module = require(game.ReplicatedStorage.ModuleScript)
task.spawn(function() module(arg1, arg2, etc.) end)
task.spawn(function() module.function(arg1, arg2, etc.) end)
That’s what my code looks like but it still wont work
Can you perhaps share your code? Else I can’t see what’s wrong.
I would imagine task.Spawn()
as like another script in a script where it runs seperately.
Not exactly the best explanation, it’s more like different threads. Because if it was another script it would not keep the environment… You can best imagine it like one script is running two functions at the same time (because that’s literally what happens).
I ended up just putting task.spawn() in the module script and everything worked perfectly
FYI, task.spawn
is a variadic function. It takes in a thread to resume or a function reference to create a thread for. What proceeds this first argument is forwarded to the threaded function. You can simplify the following:
local module = require(game.ReplicatedStorage.ModuleScript)
task.spawn(module, argument1, argument2, ...) -- If the module returns a function.
task.spawn(module.function, argument1, argument2, ...) -- If the module returns a table containing a function.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.