-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.rbxlx
5638 lines (5310 loc) · 158 KB
/
main.rbxlx
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<roblox version="4">
<Item class="ReplicatedStorage" referent="0">
<Properties>
<string name="Name">ReplicatedStorage</string>
</Properties>
<Item class="Folder" referent="1">
<Properties>
<string name="Name">TS</string>
</Properties>
<Item class="ModuleScript" referent="2">
<Properties>
<string name="Name">globals</string>
<string name="Source"><![CDATA[-- Compiled with roblox-ts v1.0.0-beta.4
local globals = {
renderDistance = 32,
blockSize = Vector3.new(3, 3, 3),
reachLength = 3 * 5,
textures = {
grid = "rbxassetid://5009068659",
grass_top = "rbxassetid://5295578161",
grass_side = "rbxassetid://5295598324",
dirt = "rbxassetid://5295593115",
brick = "rbxassetid://5295595753",
stone = "rbxassetid://5295590108",
obsidian = "rbxassetid://5295587145",
},
chunkSize = Vector2.new(16, 16),
simplexNoiseDividend = 36,
simplexNoiseScale = 1.75,
primaryGenerationHeight = 15,
dirtToStoneHeight = 7,
}
local default = globals
return {
default = default,
}
]]></string>
</Properties>
</Item>
<Item class="ModuleScript" referent="3">
<Properties>
<string name="Name">isBlockReachable</string>
<string name="Source"><![CDATA[-- Compiled with roblox-ts v1.0.0-beta.4
local TS = require(game:GetService("ReplicatedStorage"):WaitForChild("rbxts_include"):WaitForChild("RuntimeLib"))
local globals = TS.import(script, game:GetService("ReplicatedStorage"), "TS", "globals").default
--[[
*
* Checks if a block is reachable against globals.reachLength. Returns true if so.
* @param blockPosition The block's position
* @param playerPosition The player's position
]]
local function isBlockReachable(blockPosition, playerPosition)
local _0 = blockPosition
local _1 = globals.blockSize
local blockRealPos = _0 * _1
local _2 = playerPosition
local _3 = blockPosition
local distanceFromBlockToPlr = (_2 - _3).Magnitude
if distanceFromBlockToPlr <= globals.reachLength then
return true
end
return false
end
return {
isBlockReachable = isBlockReachable,
}
]]></string>
</Properties>
</Item>
</Item>
<Item class="Folder" referent="4">
<Properties>
<string name="Name">rbxts_include</string>
</Properties>
<Item class="ModuleScript" referent="5">
<Properties>
<string name="Name">Promise</string>
<string name="Source"><![CDATA[--[[
An implementation of Promises similar to Promise/A+.
Forked from LPGhatguy/roblox-lua-promise, modified for roblox-ts.
]]
local PROMISE_DEBUG = false
--[[
Packs a number of arguments into a table and returns its length.
Used to cajole varargs without dropping sparse values.
]]
local function pack(...)
local len = select("#", ...)
return len, { ... }
end
--[[
wpcallPacked is a version of xpcall that:
* Returns the length of the result first
* Returns the result packed into a table
* Passes extra arguments through to the passed function; xpcall doesn't
* Issues a warning if PROMISE_DEBUG is enabled
]]
local function wpcallPacked(f, ...)
local argsLength, args = pack(...)
local body = function()
return f(unpack(args, 1, argsLength))
end
local resultLength, result = pack(xpcall(body, debug.traceback))
-- If promise debugging is on, warn whenever a pcall fails.
-- This is useful for debugging issues within the Promise implementation
-- itself.
if PROMISE_DEBUG and not result[1] then
warn(result[2])
end
return resultLength, result
end
--[[
Creates a function that invokes a callback with correct error handling and
resolution mechanisms.
]]
local function createAdvancer(callback, resolve, reject)
return function(...)
local resultLength, result = wpcallPacked(callback, ...)
local ok = result[1]
if ok then
resolve(unpack(result, 2, resultLength))
else
reject(unpack(result, 2, resultLength))
end
end
end
local function isEmpty(t)
return next(t) == nil
end
local function createSymbol(name)
assert(type(name) == "string", "createSymbol requires `name` to be a string.")
local symbol = newproxy(true)
getmetatable(symbol).__tostring = function()
return ("Symbol(%s)"):format(name)
end
return symbol
end
local PromiseMarker = createSymbol("PromiseMarker")
local Promise = {}
Promise.prototype = {}
Promise.__index = Promise.prototype
Promise.Status = {
Started = createSymbol("Started"),
Resolved = createSymbol("Resolved"),
Rejected = createSymbol("Rejected"),
Cancelled = createSymbol("Cancelled"),
}
--[[
Constructs a new Promise with the given initializing callback.
This is generally only called when directly wrapping a non-promise API into
a promise-based version.
The callback will receive 'resolve' and 'reject' methods, used to start
invoking the promise chain.
For example:
local function get(url)
return Promise.new(function(resolve, reject)
spawn(function()
resolve(HttpService:GetAsync(url))
end)
end)
end
get("https://google.com")
:andThen(function(stuff)
print("Got some stuff!", stuff)
end)
Second parameter, parent, is used internally for tracking the "parent" in a
promise chain. External code shouldn't need to worry about this.
]]
function Promise.new(callback, parent)
if parent ~= nil and not Promise.is(parent) then
error("Argument #2 to Promise.new must be a promise or nil", 2)
end
local self = {
-- Used to locate where a promise was created
_source = debug.traceback(),
-- A tag to identify us as a promise
[PromiseMarker] = true,
_status = Promise.Status.Started,
-- A table containing a list of all results, whether success or failure.
-- Only valid if _status is set to something besides Started
_values = nil,
-- Lua doesn't like sparse arrays very much, so we explicitly store the
-- length of _values to handle middle nils.
_valuesLength = -1,
-- If an error occurs with no observers, this will be set.
_unhandledRejection = false,
-- Queues representing functions we should invoke when we update!
_queuedResolve = {},
_queuedReject = {},
_queuedFinally = {},
-- The function to run when/if this promise is cancelled.
_cancellationHook = nil,
-- The "parent" of this promise in a promise chain. Required for
-- cancellation propagation.
_parent = parent,
-- The number of consumers attached to this promise. This is needed so that
-- we don't propagate promise cancellations when there are still uncancelled
-- consumers.
_numConsumers = 0,
}
setmetatable(self, Promise)
local function resolve(...)
self:_resolve(...)
end
local function reject(...)
self:_reject(...)
end
local function onCancel(cancellationHook)
assert(type(cancellationHook) == "function", "onCancel must be called with a function as its first argument.")
if self._status == Promise.Status.Cancelled then
cancellationHook()
else
self._cancellationHook = cancellationHook
end
end
local _, result = wpcallPacked(callback, resolve, reject, onCancel)
local ok = result[1]
local err = result[2]
if not ok and self._status == Promise.Status.Started then
reject(err)
end
return self
end
--[[
Fast spawn: Spawns a thread with predictable timing.
Runs immediately instead of first cycle being deferred.
]]
function Promise.spawn(callback, ...)
local spawnBindable = Instance.new("BindableEvent")
local args = { ... }
local length = select("#", ...)
spawnBindable.Event:Connect(function()
callback(unpack(args, 1, length))
end)
spawnBindable:Fire()
spawnBindable:Destroy()
end
--[[
Create a promise that represents the immediately resolved value.
]]
function Promise.resolve(value)
return Promise.new(function(resolve)
resolve(value)
end)
end
--[[
Create a promise that represents the immediately rejected value.
]]
function Promise.reject(value)
return Promise.new(function(_, reject)
reject(value)
end)
end
--[[
Returns a new promise that:
* is resolved when all input promises resolve
* is rejected if ANY input promises reject
]]
function Promise.all(promises)
if type(promises) ~= "table" then
error("Please pass a list of promises to Promise.all", 2)
end
-- If there are no values then return an already resolved promise.
if #promises == 0 then
return Promise.resolve({})
end
-- We need to check that each value is a promise here so that we can produce
-- a proper error rather than a rejected promise with our error.
for i = 1, #promises do
if not Promise.is(promises[i]) then
error(("Non-promise value passed into Promise.all at index #%d"):format(i), 2)
end
end
return Promise.new(function(resolve, reject)
-- An array to contain our resolved values from the given promises.
local resolvedValues = {}
-- Keep a count of resolved promises because just checking the resolved
-- values length wouldn't account for promises that resolve with nil.
local resolvedCount = 0
-- Called when a single value is resolved and resolves if all are done.
local function resolveOne(i, ...)
resolvedValues[i] = ...
resolvedCount = resolvedCount + 1
if resolvedCount == #promises then
resolve(resolvedValues)
end
end
-- We can assume the values inside `promises` are all promises since we
-- checked above.
for i = 1, #promises do
promises[i]:andThen(
function(...)
resolveOne(i, ...)
end,
function(...)
reject(...)
end
)
end
end)
end
--[[
Is the given object a Promise instance?
]]
function Promise.is(object)
if type(object) ~= "table" then
return false
end
return object[PromiseMarker] == true
end
function Promise.prototype:getStatus()
return self._status
end
function Promise.prototype:isRejected()
return self._status == Promise.Status.Rejected
end
function Promise.prototype:isResolved()
return self._status == Promise.Status.Resolved
end
function Promise.prototype:isPending()
return self._status == Promise.Status.Started
end
function Promise.prototype:isCancelled()
return self._status == Promise.Status.Cancelled
end
--[[
Creates a new promise that receives the result of this promise.
The given callbacks are invoked depending on that result.
]]
function Promise.prototype:andThen(successHandler, failureHandler)
self._unhandledRejection = false
self._numConsumers = self._numConsumers + 1
-- Create a new promise to follow this part of the chain
return Promise.new(function(resolve, reject)
-- Our default callbacks just pass values onto the next promise.
-- This lets success and failure cascade correctly!
local successCallback = resolve
if successHandler then
successCallback = createAdvancer(successHandler, resolve, reject)
end
local failureCallback = reject
if failureHandler then
failureCallback = createAdvancer(failureHandler, resolve, reject)
end
if self._status == Promise.Status.Started then
-- If we haven't resolved yet, put ourselves into the queue
table.insert(self._queuedResolve, successCallback)
table.insert(self._queuedReject, failureCallback)
elseif self._status == Promise.Status.Resolved then
-- This promise has already resolved! Trigger success immediately.
successCallback(unpack(self._values, 1, self._valuesLength))
elseif self._status == Promise.Status.Rejected then
-- This promise died a terrible death! Trigger failure immediately.
failureCallback(unpack(self._values, 1, self._valuesLength))
elseif self._status == Promise.Status.Cancelled then
-- We don't want to call the success handler or the failure handler,
-- we just reject this promise outright.
reject("Promise is cancelled")
end
end, self)
end
--[[
Used to catch any errors that may have occurred in the promise.
]]
function Promise.prototype:catch(failureCallback)
return self:andThen(nil, failureCallback)
end
--[[
Cancels the promise, disallowing it from rejecting or resolving, and calls
the cancellation hook if provided.
]]
function Promise.prototype:cancel()
if self._status ~= Promise.Status.Started then
return
end
self._status = Promise.Status.Cancelled
if self._cancellationHook then
self._cancellationHook()
end
if self._parent then
self._parent:_consumerCancelled()
end
self:_finalize()
end
--[[
Used to decrease the number of consumers by 1, and if there are no more,
cancel this promise.
]]
function Promise.prototype:_consumerCancelled()
self._numConsumers = self._numConsumers - 1
if self._numConsumers <= 0 then
self:cancel()
end
end
--[[
Used to set a handler for when the promise resolves, rejects, or is
cancelled. Returns a new promise chained from this promise.
]]
function Promise.prototype:finally(finallyHandler)
self._numConsumers = self._numConsumers + 1
-- Return a promise chained off of this promise
return Promise.new(function(resolve, reject)
local finallyCallback = resolve
if finallyHandler then
finallyCallback = createAdvancer(finallyHandler, resolve, reject)
end
if self._status == Promise.Status.Started then
-- The promise is not settled, so queue this.
table.insert(self._queuedFinally, finallyCallback)
else
-- The promise already settled or was cancelled, run the callback now.
finallyCallback()
end
end, self)
end
--[[
Yield until the promise is completed.
This matches the execution model of normal Roblox functions.
]]
function Promise.prototype:await()
self._unhandledRejection = false
if self._status == Promise.Status.Started then
local result
local resultLength
local bindable = Instance.new("BindableEvent")
self:andThen(
function(...)
resultLength, result = pack(...)
bindable:Fire(true)
end,
function(...)
resultLength, result = pack(...)
bindable:Fire(false)
end
)
self:finally(function()
bindable:Fire(nil)
end)
local ok = bindable.Event:Wait()
bindable:Destroy()
if ok == nil then
-- If cancelled, we return nil.
return nil
end
return ok, unpack(result, 1, resultLength)
elseif self._status == Promise.Status.Resolved then
return true, unpack(self._values, 1, self._valuesLength)
elseif self._status == Promise.Status.Rejected then
return false, unpack(self._values, 1, self._valuesLength)
end
-- If the promise is cancelled, fall through to nil.
return nil
end
--[[
Intended for use in tests.
Similar to await(), but instead of yielding if the promise is unresolved,
_unwrap will throw. This indicates an assumption that a promise has
resolved.
]]
function Promise.prototype:_unwrap()
if self._status == Promise.Status.Started then
error("Promise has not resolved or rejected.", 2)
end
local success = self._status == Promise.Status.Resolved
return success, unpack(self._values, 1, self._valuesLength)
end
function Promise.prototype:_resolve(...)
if self._status ~= Promise.Status.Started then
return
end
-- If the resolved value was a Promise, we chain onto it!
if Promise.is((...)) then
-- Without this warning, arguments sometimes mysteriously disappear
if select("#", ...) > 1 then
local message = (
"When returning a Promise from andThen, extra arguments are " ..
"discarded! See:\n\n%s"
):format(
self._source
)
warn(message)
end
(...):andThen(
function(...)
self:_resolve(...)
end,
function(...)
self:_reject(...)
end
)
return
end
self._status = Promise.Status.Resolved
self._valuesLength, self._values = pack(...)
-- We assume that these callbacks will not throw errors.
for _, callback in ipairs(self._queuedResolve) do
callback(...)
end
self:_finalize()
end
function Promise.prototype:_reject(...)
if self._status ~= Promise.Status.Started then
return
end
self._status = Promise.Status.Rejected
self._valuesLength, self._values = pack(...)
-- If there are any rejection handlers, call those!
if not isEmpty(self._queuedReject) then
-- We assume that these callbacks will not throw errors.
for _, callback in ipairs(self._queuedReject) do
callback(...)
end
else
-- At this point, no one was able to observe the error.
-- An error handler might still be attached if the error occurred
-- synchronously. We'll wait one tick, and if there are still no
-- observers, then we should put a message in the console.
self._unhandledRejection = true
local err = tostring((...))
spawn(function()
-- Someone observed the error, hooray!
if not self._unhandledRejection then
return
end
-- Build a reasonable message
local message = ("Unhandled promise rejection:\n\n%s\n\n%s"):format(
err,
self._source
)
warn(message)
end)
end
self:_finalize()
end
--[[
Calls any :finally handlers. We need this to be a separate method and
queue because we must call all of the finally callbacks upon a success,
failure, *and* cancellation.
]]
function Promise.prototype:_finalize()
for _, callback in ipairs(self._queuedFinally) do
-- Purposefully not passing values to callbacks here, as it could be the
-- resolved values, or rejected errors. If the developer needs the values,
-- they should use :andThen or :catch explicitly.
callback()
end
end
return Promise
]]></string>
</Properties>
</Item>
<Item class="ModuleScript" referent="6">
<Properties>
<string name="Name">RuntimeLib</string>
<string name="Source"><![CDATA[local Promise = require(script.Parent.Promise)
local RunService = game:GetService("RunService")
local ReplicatedFirst = game:GetService("ReplicatedFirst")
local TS = {}
-- runtime classes
TS.Promise = Promise
local Symbol do
Symbol = {}
Symbol.__index = Symbol
setmetatable(Symbol, {
__call = function(_, description)
local self = setmetatable({}, Symbol)
self.description = "Symbol(" .. (description or "") .. ")"
return self
end
})
local symbolRegistry = setmetatable({}, {
__index = function(self, k)
self[k] = Symbol(k)
return self[k]
end
})
function Symbol:toString()
return self.description
end
Symbol.__tostring = Symbol.toString
-- Symbol.for
function Symbol.getFor(key)
return symbolRegistry[key]
end
function Symbol.keyFor(goalSymbol)
for key, symbol in pairs(symbolRegistry) do
if symbol == goalSymbol then
return key
end
end
end
end
TS.Symbol = Symbol
TS.Symbol_iterator = Symbol("Symbol.iterator")
local function isPlugin(object)
return RunService:IsStudio() and object:FindFirstAncestorWhichIsA("Plugin") ~= nil
end
-- module resolution
function TS.getModule(object, moduleName)
if RunService:IsRunning() and object:IsDescendantOf(ReplicatedFirst) then
warn("roblox-ts packages should not be used from ReplicatedFirst!")
end
-- ensure modules have fully replicated
if RunService:IsRunning() and RunService:IsClient() and not isPlugin(object) and not game:IsLoaded() then
game.Loaded:Wait()
end
local globalModules = script.Parent:FindFirstChild("node_modules")
if not globalModules then
error("Could not find any modules!", 2)
end
repeat
local modules = object:FindFirstChild("node_modules")
if modules then
local module = modules:FindFirstChild(moduleName)
if module then
return module
end
end
object = object.Parent
until object == nil or object == globalModules
return globalModules:FindFirstChild(moduleName) or error("Could not find module: " .. moduleName, 2)
end
-- This is a hash which TS.import uses as a kind of linked-list-like history of [Script who Loaded] -> Library
local currentlyLoading = {}
local registeredLibraries = {}
function TS.import(caller, module, ...)
for i = 1, select("#", ...) do
module = module:WaitForChild((select(i, ...)))
end
if module.ClassName ~= "ModuleScript" then
error("Failed to import! Expected ModuleScript, got " .. module.ClassName, 2)
end
currentlyLoading[caller] = module
-- Check to see if a case like this occurs:
-- module -> Module1 -> Module2 -> module
-- WHERE currentlyLoading[module] is Module1
-- and currentlyLoading[Module1] is Module2
-- and currentlyLoading[Module2] is module
local currentModule = module
local depth = 0
while currentModule do
depth = depth + 1
currentModule = currentlyLoading[currentModule]
if currentModule == module then
local str = currentModule.Name -- Get the string traceback
for _ = 1, depth do
currentModule = currentlyLoading[currentModule]
str = str .. " ⇒ " .. currentModule.Name
end
error("Failed to import! Detected a circular dependency chain: " .. str, 2)
end
end
if not registeredLibraries[module] then
if _G[module] then
error("Invalid module access! Do you have two TS runtimes trying to import this? " .. module:GetFullName(), 2)
end
_G[module] = TS
registeredLibraries[module] = true -- register as already loaded for subsequent calls
end
local data = require(module)
if currentlyLoading[caller] == module then -- Thread-safe cleanup!
currentlyLoading[caller] = nil
end
return data
end
function TS.exportNamespace(module, ancestor)
for key, value in pairs(module) do
ancestor[key] = value
end
end
-- general utility functions
function TS.instanceof(obj, class)
-- custom Class.instanceof() check
if type(class) == "table" and type(class.instanceof) == "function" then
return class.instanceof(obj)
end
-- metatable check
if type(obj) == "table" then
obj = getmetatable(obj)
while obj ~= nil do
if obj == class then
return true
end
local mt = getmetatable(obj)
if mt then
obj = mt.__index
else
obj = nil
end
end
end
return false
end
function TS.async(callback)
return function(...)
local n = select("#", ...)
local args = { ... }
return Promise.new(function(resolve, reject)
coroutine.wrap(function()
local ok, result = pcall(callback, unpack(args, 1, n))
if ok then
resolve(result)
else
reject(result)
end
end)()
end)
end
end
local function package(...)
return select("#", ...), {...}
end
function TS.await(promise)
if not Promise.is(promise) then
return promise
end
local size, result = package(promise:await())
local ok = table.remove(result, 1)
if ok then
if size > 2 then
return result
else
return result[1]
end
else
error(ok == nil and "The awaited Promise was cancelled" or (size > 2 and result[1] or result), 2)
end
end
function TS.add(a, b)
if type(a) == "string" or type(b) == "string" then
return a .. b
else
return a + b
end
end
function TS.bit_lrsh(a, b)
local absA = math.abs(a)
local result = bit32.rshift(absA, b)
if a == absA then
return result
else
return -result - 1
end
end
TS.TRY_RETURN = 1
TS.TRY_BREAK = 2
TS.TRY_CONTINUE = 3
function TS.try(func, catch, finally)
local err, traceback
local success, exitType, returns = xpcall(
func,
function(errInner)
err = errInner
traceback = debug.traceback()
end
)
if not success and catch then
local newExitType, newReturns = catch(err, traceback)
if newExitType then
exitType, returns = newExitType, newReturns
end
end
if finally then
local newExitType, newReturns = finally()
if newExitType then
exitType, returns = newExitType, newReturns
end
end
return exitType, returns
end
function TS.generator(callback)
local co = coroutine.create(callback)
return {
next = function(...)
if coroutine.status(co) == "dead" then
return { done = true }
else
local success, value = coroutine.resume(co, ...)
if success == false then
error(value, 2)
end
return {
value = value,
done = coroutine.status(co) == "dead"
}
end
end
}
end
-- LEGACY RUNTIME FUNCTIONS
local HttpService = game:GetService("HttpService")
-- utility functions
local function copy(object)
local result = {}
for k, v in pairs(object) do
result[k] = v
end
return result
end
local function deepCopyHelper(object, encountered)
local result = {}
encountered[object] = result
for k, v in pairs(object) do
if type(k) == "table" then
k = encountered[k] or deepCopyHelper(k, encountered)
end
if type(v) == "table" then
v = encountered[v] or deepCopyHelper(v, encountered)
end
result[k] = v
end
return result
end
local function deepCopy(object)
return deepCopyHelper(object, {})
end
local function deepEquals(a, b)
-- a[k] == b[k]
for k in pairs(a) do
local av = a[k]
local bv = b[k]
if type(av) == "table" and type(bv) == "table" then
local result = deepEquals(av, bv)
if not result then
return false
end
elseif av ~= bv then
return false
end
end
-- extra keys in b
for k in pairs(b) do
if a[k] == nil then
return false
end
end