-
Notifications
You must be signed in to change notification settings - Fork 1
/
asyncloader.lua
65 lines (56 loc) · 1.66 KB
/
asyncloader.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
65
local LoadContent =
{
loadFunc = nil,
onLoad = nil,
contentName = ""
}
function LoadContent.new(func, onLoad, contentName)
local obj = setmetatable({}, LoadContent)
obj.loadFunc = func
obj.onLoad = onLoad or nil
obj.contentName = contentName or ""
return obj
end
local _coroutine = nil
asyncLoader =
{
queue = {},
resourcesLoaded = 0,
progress = 0,
currentContent = "",
hasStarted = false
}
function asyncLoader.reset()
asyncLoader.queue = {}
asyncLoader.resourcesLoaded = 0
asyncLoader.currentContent = ""
asyncLoader.progress = 1
asyncLoader.hasStarted = false
end
function asyncLoader.loadFunc(loadFunction, onLoad, contentName)
table.insert(asyncLoader.queue, LoadContent.new(loadFunction, onLoad, contentName))
end
function asyncLoader.startLoading(onResourcesLoaded)
asyncLoader.hasStarted = true
asyncLoader.currentContent = asyncLoader.queue[1].contentName
_coroutine = coroutine.create(function()
for i, loadContent in ipairs(asyncLoader.queue) do
loadContent.loadFunc()
if(loadContent.onLoad) then loadContent.onLoad() end
asyncLoader.resourcesLoaded = i
if(i ~= #asyncLoader.queue) then
asyncLoader.currentContent = asyncLoader.queue[i+1].contentName
end
asyncLoader.progress = asyncLoader.resourcesLoaded / #asyncLoader.queue
coroutine.yield()
end
_coroutine = nil
asyncLoader.reset()
if(onResourcesLoaded) then onResourcesLoaded() end
end)
end
function asyncLoader.update(dt)
if (_coroutine) then
coroutine.resume(_coroutine)
end
end