coroutine.create

From Garry's Mod
Revision as of 23:01, 9 March 2017 by EstevanTH (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
 coroutine.create( )

Contents

Description

Creates a coroutine of the given function.

Arguments

function func

The function for the coroutine to use

Returns

thread

coroutine

Examples

Example

Display the location of each player in an endless loop, but only one player per frame.

do
	local function displayer()
		local players
		while true do -- endless loop: you must guarantee that coroutine.yield() is always called!
			players = player.GetAll()
			if not next( players ) then -- empty table
				coroutine.yield() -- guarantee a pause in coroutine even with an empty table
			else
				for _, ply in pairs( players ) do
					coroutine.yield() -- We yield here so what you may do next will start immediatly when this for loop finishes.
					if IsValid( ply ) then -- The player ply may be disconnected now!
						print( ply:Nick(), "is located at", ply:GetPos() )
					end
				end
				
			end
		end
	end
	
	local co
	hook.Add( "Think", "DisplayPlayersLocation", function()
		if not co or not coroutine.resume( co ) then
			co = coroutine.create( displayer )
			coroutine.resume( co )
		end
	end )
end

Output:

Custom Nickname	is located at	10.102 59.04 -100.96
SuperBoss	is located at	55.85 1209.11 -100.96
Custom Nickname	is located at	11.126 51.92 -100.96
...
Personal tools
Navigation