Garry's Mod Wiki

Revision Difference

coroutine.create#527960

<function name="create" parent="coroutine" type="libraryfunc"> <description>Creates a coroutine of the given function.</description> <realm>Shared and Menu</realm> <args> <arg name="func" type="function">The function for the coroutine to use</arg>⤶ <arg name="func" type="function">The function for the coroutine to use.</arg>⤶ </args> <rets> <ret name="" type="thread">coroutine</ret> </rets> </function> <example> <description>Display the location of each player in an endless loop, but only one player per frame.</description> <code> 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⤶ 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 ipairs( 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⤶ </code>⤶ <outputfixedwidth>Fixed width</outputfixedwidth>⤶ 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 ) </code>⤶ <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 ... ```⤶ </output> ⤶ </example></example>