Problem with spawn()

how to pass argument using spawn()

8 Likes

You can’t pass arguments to the function with spawn. If you want to pass arguments to the function coroutines would be required.

local function SpawnWithArguments(f,...)
    local delta,elapsed = wait()
    f(delta,elapsed,...)
end
--later on
coroutine.wrap(SpawnWithArguments)(f,...--[[arguments]])
3 Likes

You cannot pass arguments with spawn. If you want to call a function with arguments on a sepparate thread, you will need to call it inside another function.

local functocall = function(a,b)
print(a,b)
end

spawn(function() functocall(1,2) end)

Or as @Halalaluyafail3 said, use coroutines.

EDIT: For anyone still looking at this archaic response, the task.spawn function does support parsing arguments.

task.spawn(funcname, arg1, arg2, ...)

25 Likes

Continuing on with coroutines, you can use create and resume - which accepts arguments:

local function foo(...)
    print(...)
end

coroutine.resume(coroutine.create(foo), "Hello ", "World!")
3 Likes

You know that you can directly wrap print, right? Creating another function just to run print is unnecessary. You don’t need the spaces in the strings either, the arguments passed to print are automatically concatenated with a space.

coroutine.resume(coroutine.create(print), "Hello", "World!")
1 Like