fork/m-overlay

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

BkacjiosSmall fixes6107ffc

v2.1.3
1.4 KiB58 linesraw
1local downloader = {}
2
3local REQUESTS = {}
4
5local log = require("log")
6
7local THREAD = love.thread.newThread("modules/downloader/thread.lua")
8THREAD:start()
9
10-- these two channels are used to send requests and progress updates back and forth
11local requests_channel = love.thread.getChannel("dl-requests")
12local progress_channel = love.thread.getChannel("dl-progress")
13
14function downloader.request(request, callback)
15	for id=1,#REQUESTS+1 do
16		-- find a nil table entry
17		if REQUESTS[id] == nil then
18			-- save our callback with ID as the key
19			REQUESTS[id] = callback
20			-- push our request to the web-requests thread channel
21			requests_channel:push({id=id,request=request})
22			break
23		end
24	end
25end
26
27function downloader.download(url, filename, callback)
28	local request = {
29		url = url,
30		filename = filename
31	}
32	downloader.request(request, callback)
33end
34
35-- poll the progress channel for updates
36function downloader.update()
37	while progress_channel:peek() do
38		-- got response from channel
39		local pop = progress_channel:pop()
40		local id = pop.id
41		local callback = REQUESTS[id]
42		if pop.event and pop.event.code then
43			-- we got a status code, delete the callback
44			REQUESTS[id] = nil
45		end
46		local succ, err = xpcall(callback, debug.traceback, pop.event)
47		if not succ then
48			-- calling our callback resulted in an error
49			log.error("[DOWNLOADER] callback error: %s", err)
50		end
51	end
52end
53
54function downloader.close()
55	requests_channel:push(false)
56end
57
58return downloader