coroutine.wrap
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.