-
Notifications
You must be signed in to change notification settings - Fork 11
/
coro-utils.lua
64 lines (51 loc) · 1.39 KB
/
coro-utils.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
-- from incredible-gmod.ru with <3
-- https://github.com/Be1zebub/Small-GLua-Things/blob/master/coro-utils.lua
--[[ Example:
coroutine.wrap(function()
print(SysTime())
coroutine.pause(1.5)
print(SysTime())
local succ, response, headers, code = coroutine.httpFetch("https://incredible-gmod.ru/ping.php")
if succ then
print("coroutine.httpFetch response: ".. response)
else
print("coroutine.httpFetch fail - reason: ".. response)
end
end)()
]]--
function coroutine.pause(delay)
local co = coroutine.running()
timer.Simple(delay, function()
coroutine.resume(co)
end)
coroutine.yield()
end
function coroutine.async(fn)
return function(...)
local co = coroutine.running()
fn(function(succ, err, ...)
if succ == false then
ErrorNoHaltWithStack(err .."\n")
end
coroutine.resume(co, err, ...)
end, ...)
return coroutine.yield()
end
end
coroutine.http = setmetatable({}, {
__call = coroutine.async(function(cback, HTTPRequest)
HTTPRequest.success = function(code, body, headers)
cback(true, body, headers, code)
end
HTTPRequest.failed = function(err)
cback(false, err)
end
HTTP(HTTPRequest)
end, false)
})
function coroutine.http.fetch(url, headers)
return coroutine.http({method = "GET", url = url, headers = headers})
end
function coroutine.http.post(url, headers, body)
return coroutine.http({method = "POST", url = url, headers = headers, body = body})
end