“Spawn function requires 1 argument”
spawn(thefunction(cframe))
“Spawn function requires 1 argument”
spawn(thefunction(cframe))
You should be using task.spawn() instead, it’s the new and better version of deprecated version of spawn()
okay then how do I use task.spawn()?
task.spawn(function()
--code
end)
You are trying to call the result of the function thefunction
, instead do either spawn(thefunction)
or
spawn(function()
thefunction(cframe)
end)
And as @KultDeeri said, use task.spawn
as it is newer and more efficient.
So I can’t just spawn a function, I have to make a function to spawn a function? I want to spawn the I made, not make another
or you can do like
local function test()
print('test')
end
task.spawn(test)
Why is task better than normal?
you dont have to, you can also use a function inside the the brackets.
because task is half times faster than the normal version, and task.spawn doesnt have a built in wait() inside it’s function while spawn() has one.
They are more optimized to run in-time with the TaskScheduler
, meaning less lag and faster execution times.
https://developer.roblox.com/en-us/api-reference/lua-docs/task
You can also pass arguments as extra parameters.
local function exampleSpawn(param1, param2, ...)
local extraParams = {...}
end
task.spawn(exampleSpawn, 32, true, table.unpack(table.create(5, true)))
This would first evaluate thefunction(cframe)
before passing the result of this function as an argument to spawn (which would error unless it returned a function). spawn(thefunction, cframe)
however would run function thefunction
with parameter cframe
.
you all didnt actually tell him what it does, basically, it allows you to multithread by creating a thread with a specific function, this is useful for doing multiple loops, lengthy and heavy tasks, and etc. this is the importance of spawn.
Now, how do we use it? Its simple.
lets say i wanna do some heavy task like generate large ids for each people, so we do this=
local ids = {}
local people = {"me", "noob", "dog"}
local function generateid(person)
local id = 0
local powby = 0
while id > 888 do
id = id ^ powby
powby = powby + math.random(5, 88)
wait()
end
ids[person] = id
end
for _,v in pairs(people) do
--lets assume this generateid function is heavy and lenthy task. so multithread
spawn(generateid, v) -- spawn requires a function as an argument
-- the rest of the arguments are the arguments to pass to the function
end
for i,v in pairs(ids) do
print(i, v)
end -- prints ids
you might want to use task.spawn
as it suspreded spawn. but i hope you know the importance of spawn and how to use it.
important note: true multithreading dosent exist in lua, so we cant really pause the threads and threads will still exist until it stopped. so think wisely before using the function.