fork/m-overlay

git clone https://git.julia.blue/fork/m-overlay

BkacjiosSmall fixes6107ffc

main
1.6 KiB69 linesraw
1local web = {}
2
3local log = require("log")
4
5local REQUESTS = {}
6local THREAD_POOL_SIZE = 3
7
8local THREAD = love.thread.newThread("modules/web/thread.lua")
9THREAD:start()
10
11-- these two channels are used to send requests and progress updates back and forth
12local requests_channel = love.thread.getChannel("web-requests")
13local progress_channel = love.thread.getChannel("web-progress")
14
15-- main request method
16function web.request(request, callback)
17	for id=1,#REQUESTS+1 do
18		-- find a nil table entry
19		if REQUESTS[id] == nil then
20			-- save our callback with ID as the key
21			REQUESTS[id] = callback
22			-- push our request to the web-requests thread channel
23			requests_channel:push({id=id,request=request})
24			break
25		end
26	end
27end
28
29-- helper function for a GET request
30function web.get(url, callback)
31	local request = {
32		method = "GET",
33		url = url
34	}
35	web.request(request, callback)
36end
37
38-- helper function for a POST request
39function web.post(url, body, headers, callback)
40	local request = {
41		method = "POST",
42		url = url,
43		body = body,
44		headers = headers
45	}
46	web.request(request, callback)
47end
48
49-- poll the progress channel for updates
50function web.update()
51	while progress_channel:peek() do
52		-- got response from channel
53		local pop = progress_channel:pop()
54		local id = pop.id
55		local callback = REQUESTS[id]
56		local succ, err = xpcall(callback, debug.traceback, pop.event)
57		if not succ then
58			-- calling our callback resulted in an error
59			log.error("[WEB] callback error: %s", err)
60		end
61		REQUESTS[id] = nil
62	end
63end
64
65function web.close()
66	requests_channel:push(false) -- false ends the thread loop
67end
68
69return web