fork/m-overlay

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

BkacjiosSmall fixes6107ffc

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