Garry's Mod Wiki

coroutine.wrap

  function coroutine.wrap( function coroutine )

Description

Returns a function which calling is equivalent with calling coroutine.resume with the coroutine and all extra parameters.

The values returned by the returned function only contain the values passed to the inner coroutine.yield call and do not include the no error status that coroutine.resume provides. In case of failure, an error is thrown instead.

Arguments

1 function coroutine
Coroutine to resume.

Returns

Example

Performs a standard HTTP request while waiting for the server response to continue executing the code. Useful to improve the readability of the code and avoid using callback functions.

local function HTTPRequest( url, headers ) local running = coroutine.running() local function onSuccess( body, length, header, code ) coroutine.resume( running, true, body ) end local function onFailure( err ) coroutine.resume( running, false, err ) end http.Fetch( url, onSuccess, onFailure, headers ) return coroutine.yield() end coroutine.wrap( function() local state, response = HTTPRequest( "https://www.google.com/" ) if state then -- Success! print( "HTTP body:" .. response ) else -- Error(?) print( "HTTP request error: " .. response ) end -- Important code to be performed after the request is completed.. end )()
Output: The body of the HTTP page if the request was successful, otherwise the error code in case of failure.