Use of task.spawn

Attempting to utilize task.spawn here, unfortunately I’m not quite sure how to properly use it, say I have the example code below.

function testing(player)
      print(player.Name)
end

-- player gets defined here
task.spawn(testing(player)) -- attempt to spawn new thread with contents function

The code will toss an error saying:
invalid argument #1 to ‘spawn’ (function or thread expected)

so I’m doing something wrong here, can anyone clear it up for me?

3 Likes

You would essentially be trying to spawn a new thread of the returned value of the function, which in this case would be nil/nothing since the function returns nothing.

1 Like

task.spawn takes a function (or a thread) as its parameter. If you have no function or thread to pass you can create and pass a blank one with their type constructor functions (function() end and coroutine.create() respectively).

Your code is attempting to pass an active function call as the parameter (which returns nothing; and thus, no end argument is given).

The real solution here is higher order function work- which basically means functions that manipulate other functions. You can do this in your example like so:

function Testing(Player) -- Higher order function which returns an inactive function.
	return function()
		print(Player.Name) -- Player is accessible as an upvalue.
	end
end

task.spawn( Testing "Test" )

The alternative is to use an empty function argument:

local Player = nil -- Player should be accessible here in theory.
task.spawn(function() print(Player.Name) end)

This is just a problem with understanding Lua syntax, and you will get better at it with time.

33 Likes

Awesome, that really clears up quite a lot actually. Thankful that your answer hit all bases of the problem and clearly addressed the context of what I’m doing.

1 Like

This method also works. Just put the arguments after the function instead of in parentheses.

task.spawn(testing, player)

20 Likes

Ah okay, good to know. Unfortunately I haven’t been able to pull up any good documentation on task.spawn

1 Like