-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinit.lua
560 lines (413 loc) · 13.5 KB
/
init.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
_G._PATH = io.popen("cd"):read("*l")
--
-- Globalize JSON
--
require("dependencies/json")
--
-- LUA Extensions
--
require("dependencies/string")
require("dependencies/table")
require("dependencies/math")
--
-- File Validation
--
local function fileExists(path)
local file = io.open(path, "r")
if file then
file:close()
end
return file ~= nil
end
local function readFile(path)
local file = io.open(path, "r")
if file == nil then
return nil
end
local code = file:read("*a")
file:close()
return code
end
local function writeFile(path, str)
local file = io.open(path, "w+")
if file == nil then
return nil
end
file:write(str)
file:close()
return true
end
--
-- Global Config
--
local globalConfigFilePath = "data/config.json"
if not fileExists(globalConfigFilePath) then
return error("No global config file found.")
end
local globalConfigString = readFile(globalConfigFilePath) or "[]"
local globalConfig = json.decode(globalConfigString)
--
-- Exports
--
local exports = {}
local exportsMt = {
__index = function(self, resourceName)
if type(resourceName) ~= "string" then
return error("Exports must be indexed with a string value")
end
if not exports[resourceName] then
return error(string.format("No exports defined for %s. Are you sure this resource has been started?"), resourceName)
end
return setmetatable({}, {
__index = function(self, exportName)
if type(exportName) ~= "string" then
return error("Exports methods must be indexed with a string value")
end
return exports[resourceName][exportName]
end
})
end,
__call = function(self, exportName, fn)
if type(exportName) ~= "string" then
return error("Export definition requires string as the first argument")
elseif type(fn) ~= "function" then
return error("Export definition requires function as the second argument")
end
exports[self._RESOURCE] = exports[self._RESOURCE] or {}
exports[self._RESOURCE][exportName] = fn
end
}
--
-- Locales
--
local locales = {}
local function translate(self, labelName)
if not locales[self._RESOURCE] then
locales[self._RESOURCE] = LoadResourceData(self._RESOURCE, "locales/" .. globalConfig.locale .. ".json")
end
return locales[self._RESOURCE][labelName]
end
local localesMt = {
__index = translate,
__call = translate
}
--
-- Resource Loader
--
local loadResource
local loadedResources = {}
local loadResourceMt = {
__call = function(self, resourceName, options, reload)
return loadResource(self._g, resourceName, options or {}, reload)
end
}
local function createEnvironment(resourceName, version)
local _g = {}
_g._RESOURCE = resourceName
_g._VERSION = version
_g.LoadResource = setmetatable({ _g = _g }, loadResourceMt)
_g.Exports = setmetatable({ _RESOURCE = resourceName }, exportsMt)
_g.Locale = setmetatable({ _RESOURCE = resourceName }, localesMt)
local env = {}
env._G = _G
env._ENV = setmetatable(env, {
__index = function(self, k)
if _g[k] == nil then
return _G[k]
end
return _g[k]
end,
__newindex = _g
})
return env
end
local function loadScript(code, filePath, environment, ...)
local _,fn,err = pcall(load, code, filePath, 'bt', environment)
if err then
return false,err
end
if type(fn) ~= "function" then
return false
end
local res,ret = pcall(fn, ...)
if not res then
return false,ret
end
return ret
end
local function handleReturn(_g, resourceName, options, globalTable)
if not next(globalTable) then
return nil
end
if options.injectGlobal then
_g[resourceName] = globalTable
else
return globalTable
end
end
loadResource = function(_g, resourceName, options, reload)
local version = options.version or "root"
if not reload and loadedResources[resourceName] and loadedResources[resourceName][version] then
return handleReturn(_g, resourceName, options, loadedResources[resourceName][version])
end
options = options or {}
local versionPath = options.version and ("/" .. options.version) or ""
local resourcePath = _PATH .. "/modules/" .. resourceName .. versionPath
local entryFilePath = resourcePath .. "/resource.json"
if not fileExists(entryFilePath) then
return error("resource does not contain resource.json entry file: " .. resourceName)
end
local entryFileContent = readFile(entryFilePath)
if type(entryFileContent) ~= "string" then
return error("resource has invalid resource.json entry file: " .. resourceName)
end
local resourceDef = json.decode(entryFileContent)
if type(resourceDef) ~= "table" then
return error("resource has invalid resource.json entry file content: " .. resourceName)
end
local env = options.env or createEnvironment(resourceName, options.version or "default")
local globalTable = {}
for _,fileName in ipairs(resourceDef) do
local filePath = resourcePath .. "/" .. fileName .. ".lua"
if not fileExists(filePath) then
return error("defined file does not exist: " .. filePath)
end
local code = readFile(filePath)
if not code then
return error("invalid file content for: " .. filePath)
end
local res,err = loadScript(code, filePath, env)
if err then
return error(err)
end
if type(res) == "table" then
for k,v in pairs(res) do
globalTable[k] = v
end
elseif type(res) == "function" then
globalTable[fileName] = res
end
end
loadedResources[resourceName] = loadedResources[resourceName] or {}
loadedResources[resourceName][version] = globalTable
if reload then
TriggerEvent("resource_restarted", resourceName, version)
else
TriggerEvent("resource_started", resourceName, version)
end
return handleReturn(_g, resourceName, options, globalTable)
end
--
-- Events
--
local eventListeners = {}
function TriggerEvent(eventName, ...)
if type(eventName) ~= "string" then
return error("TriggerEvent requires a string [eventName] as the first argument.")
end
if not eventListeners[eventName] then
return
end
for _,callback in ipairs(eventListeners[eventName]) do
-- CreateThread(callback, ...)
callback(...)
end
end
function AddEventHandler(eventName, callback)
if type(eventName) ~= "string" then
return error("AddEventHandler requires a string [eventName] as the first argument.")
end
if type(callback) ~= "function" then
return error("AddEventHandler requires a function [callback] as the second argument.")
end
eventListeners[eventName] = eventListeners[eventName] or {}
table.insert(eventListeners[eventName], callback)
end
--
-- Native Event Handlers
--
local nativeEventListeners = {}
local nativeListener = registerForEvent
registerForEvent = nil
function RegisterForEvent(eventName, callback)
if type(eventName) ~= "string" then
return error("RegisterForEvent requires a string [eventName] as the first argument.")
end
if type(callback) ~= "function" then
return error("RegisterForEvent requires a function [callback] as the second argument.")
end
if not nativeEventListeners[eventName] then
local listeners = {}
nativeListener(eventName, function(...)
for _,callback in ipairs(listeners) do
callback(...)
end
end)
nativeEventListeners[eventName] = listeners
end
table.insert(nativeEventListeners[eventName], callback)
end
--
-- File Loader
--
function LoadResourceFile(resourceName, filePath)
if type(resourceName) ~= "string" then
return error("LoadResourceFile requires a string [resourceName] as the first argument.")
end
if type(filePath) ~= "string" then
return error("LoadResourceFile requires a string [filePath] as the second argument.")
end
local path = _PATH .. "/modules/" .. resourceName .. "/" .. filePath
if not fileExists(path) then
return ""
end
local content = readFile(path)
if type(content) ~= "string" then
return error("invalid data file content: " .. path)
end
return content
end
function SaveResourceFile(resourceName, filePath, content)
if type(resourceName) ~= "string" then
return error("SaveResourceFile requires a string [resourceName] as the first argument.")
end
if type(filePath) ~= "string" then
return error("SaveResourceFile requires a string [filePath] as the second argument.")
end
if type(content) ~= "string" then
return error("SaveResourceFile requires a string [content] as the third argument.")
end
local path = _PATH .. "/modules/" .. resourceName .. "/" .. filePath
local result = writeFile(path, content)
if not result then
return error("failed writing data to file: " .. path)
end
end
--
-- Data File Loader
--
function LoadResourceData(resourceName, filePath)
if type(resourceName) ~= "string" then
return error("LoadResourceData requires a string [resourceName] as the first argument.")
end
if type(filePath) ~= "string" then
return error("LoadResourceData requires a string [filePath] as the second argument.")
end
local content = LoadResourceFile(resourceName, filePath)
if not content then
return {}
end
return json.decode(content)
end
function SaveResourceData(resourceName, filePath, data)
if type(resourceName) ~= "string" then
return error("SaveResourceData requires a string [resourceName] as the first argument.")
end
if type(filePath) ~= "string" then
return error("SaveResourceData requires a string [filePath] as the second argument.")
end
if type(data) ~= "table" then
return error("SaveResourceData requires a table [data] as the third argument.")
end
local content = json.encode(data, { indent = true })
SaveResourceFile(resourceName, filePath, content)
end
--
-- Thread Tracker
--
-- local threads = {}
-- function CreateThread(callback, ...)
-- if type(callback) ~= "function" then
-- return error("CreateThread requires a function [callback] as the first argument.")
-- end
-- local thread = {
-- coroutine = coroutine.create(callback),
-- waitTime = -1,
-- prevTime = GetGameTimer(),
-- args = {...}
-- }
-- local function Wait(waitTime)
-- thread.waitTime = waitTime
-- coroutine.yield(thread.coroutine)
-- end
-- local env = getfenv(callback)
-- local threadMt = setmetatable({}, {
-- __index = function(self, k)
-- if k == "Wait" then
-- return Wait
-- else
-- return env[k]
-- end
-- end,
-- __newindex = env
-- })
-- setfenv(callback, threadMt)
-- table.insert(threads, thread)
-- end
-- function SetTimeout(callback, delay)
-- if type(callback) ~= "function" then
-- return error("SetTimeout requires a function [callback] as the first argument.")
-- end
-- if type(delay) ~= "number" then
-- return error("SetTimeout requires a number [delay] as the second argument.")
-- end
-- local thread = {
-- coroutine = coroutine.create(callback),
-- waitTime = delay,
-- prevTime = GetGameTimer(),
-- kill = true
-- }
-- table.insert(threads, thread)
-- end
-- local gameTime = 0
-- function GetGameTimer()
-- return math.floor(gameTime * 1000)
-- end
-- nativeListener("update", function(deltaTime)
-- gameTime = gameTime + deltaTime
-- if #threads == 0 then
-- return
-- end
-- local timeNow = GetGameTimer()
-- for i=#threads,1,-1 do
-- local thread = threads[i]
-- if thread.waitTime <= 0 or timeNow - thread.prevTime >= thread.waitTime then
-- coroutine.resume(thread.coroutine, table.unpack(thread.args))
-- if thread.kill then
-- table.remove(threads, i)
-- else
-- thread.prevTime = timeNow
-- end
-- end
-- end
-- end)
--
-- Resource Initialization
--
local initResourceFilePath = "data/resources.json"
if not fileExists(initResourceFilePath) then
return error("resources.json is not present in root directory")
end
local initResources = json.decode(readFile(initResourceFilePath) or "")
if type(initResources) ~= "table" then
return error("failed to parse resources.json file")
end
for _,resourceDef in ipairs(initResources) do
loadResource(_G, resourceDef.name, resourceDef.options or {})
end
--
-- Resource Reloader
-- TODO:
-- * Rewrite event registry system to allow removal of listeners on reload.
-- * Same for threads, kill all resource threads on reload.
--
function ReloadResource(resourceName)
local _,resourceDef = table.search(initResources, function(_, resourceDef)
return resourceDef.name == resourceName
end)
if not resourceDef then
return
end
loadResource(_G, resourceDef.name, resourceDef.options or {}, true)
print("Resource reloaded: " .. resourceName)
end