forked from R4d1o4ct1v3/XToLevel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibs.lua
694 lines (640 loc) · 21.9 KB
/
Libs.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
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
---
-- A collection of globally available functions, used througout the addon.
-- @file Libs.lua
-- @release 4.1.0_26
-- @author Atli Þór ([email protected])
---
--module "XToLevel.Lib" -- For documentation purposes. Do not uncomment!
--[[
Functions:
ZoneID() - Returns the ID of the zone the player is current in
IsPlayerRafEligable() - Determines whether the player is eligable for the 3x RAF bonus.
IsRafApplied() - Determines whether the RAF bonus should be applied.
IsInBattleground() - Determines whether the player is currently inside a battleground zone.
ShowBattlegroundData() - Determines whether the BG data should be displayed in the tooltip.
ShowDungeonData() - Determines whether the Dungeon data should be displayed in the tooltip.
MobXP(charlvl, moblvl) - Calculates the amount of XP the mob is worth to the player.
GetChatXPRegexp(isQuest) - Retrieves the proper regexp to parse a chat XP message.
ParseChatXPMessage(msg, locale) - Parses the chat XP message into XP amount and Mob name (if available).
round(input, precision, roundDown) - Rounds the input number to the given precision.
NumberFormat(input) - Formats the input number to a human-readable number. (Adds commas and periods)
ShrinkNumber(input) - Shrinks a number to a smaller format. (E.g. 1234000 = 1,23M)
DecToHex(input) - Converts a decimal (base 10) number to a hex (base 16) number.
GetProgressColor(percent) - Gets a color value to represent the given progress. (Green for 100%, red for 0%)
GetBGObjectiveMinXP() - Gets the minimum amount of XP that would be considered a valid BG objective reward.
FindAnchor(frame) - Gets the appropriate tooltip anchor point for the give frame. (E.g. "TOPLEFT", "BOTTOMRIGHT")
Split(str, delim, maxNb) - Splits the str on the delim char, maxNb number of times.
--]]
console = { }
function console:log(message)
XToLevel.Messages:Debug(message)
end
XToLevel.Lib = { }
function XToLevel.Lib:IsClassic()
local interfaceNumber = select(4, GetBuildInfo())
return interfaceNumber < 80000
-- If this check ever needs an update... I guess the corona virus didn't turn into a zombie apocalypse?
end
function XToLevel.Lib:IsBattleground()
if XToLevel.Lib.IsClassic() then
return XToLevel.Lib.GetCurrentBattlegroundName() ~= nil
else
return C_PvP.IsBattleground()
end
end
---
-- Either returns the name of the ongoing battleground, or a nil of no battleground is in progress.
function XToLevel.Lib:GetCurrentBattlegroundName()
local bgName = nil
for index=1,GetMaxBattlefieldID() do
local status, name = GetBattlefieldStatus(index)
if status == "active" then
bgName = name
end
end
return bgName
end
---
-- Counts the number of times the needle is found in the heystack.
-- @param needle The needle
-- @param heystack The heystack
function XToLevel.Lib:strcount(needle, heystack)
local index = 1
local count = 0
local startPos, endPos = strfind(heystack, needle)
while endPos ~= nil and count < 10000 do -- 10000 to avoid infinite loops
count = count + 1
index = index + endPos
startPos, endPos = strfind(strsub(heystack, index), needle)
end
return count
end
--- Converts a global message, such as FACTION_STANDING_INCREASED
-- to a regular expression that can be used to pull info
-- from messages built from them.
-- @param input The value from the global to be changed.
function XToLevel.Lib:ConvertGlobalToRegexp(input)
local reg = string.gsub(input, "(%%d)", "(%%d+)")
reg = string.gsub(reg, "(%%s)", "(.+)")
return reg
end
--- Runs through the faction list, searching for the faction who's name matches
-- the one give. If found, returns the following info, or nill otherwise:
-- desc, start, amount, current, atWar, isWatched.
-- @param searchName The name of the faction to search for.
function XToLevel.Lib:GetFactionInfoByName(searchName)
local factionIndex = 1
while factionIndex <= GetNumFactions() do
local name, description, standingId, bottomValue, topValue, earnedValue, atWarWith,
canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild = GetFactionInfo(factionIndex)
if isHeader == nil and name == searchName then
--console:log("FACTION : " .. tostring(bottomValue) .. " - " .. tostring(earnedValue) .. " - " .. tostring(topValue))
local repAmountPerLevel = nil
if bottomValue < 0 then
repAmountPerLevel = math.abs(tonumber(bottomValue)) + tonumber(topValue)
else
repAmountPerLevel = tonumber(topValue) - tonumber(bottomValue)
end
-- Read: desc, start, amount, current, atWar, isWatched.
return description, bottomValue, repAmountPerLevel, earnedValue, atWarWith, isWatched
else
ExpandFactionHeader(factionIndex)
end
factionIndex = factionIndex + 1
end
end
--- Returns the name of the current rep level, as well as those around it.
-- @param currentRep The total amount of rep the player has earned
-- @return the anme of the current level, the next level, and the previous level, in that order.
function XToLevel.Lib:GetRepLevelName(currentRep)
for index, value in ipairs(REP_LEVELS) do
if value[2] <= currentRep and (value[2] + value[3]) > currentRep then
local currentName = value[1]
local upName = nil
local downName = nil
if index > 1 then
downName = REP_LEVELS[index-1][1]
end
if index < # REP_LEVELS then
upName = REP_LEVELS[index+1][1]
end
return currentName, upName, downName
end
end
end
--- Calculates the number of rep gains needed to level.
-- @param gain The rep gained
-- @param lvlStart The start point for this level; the lower end of range.
-- @param lvlAmount The amount of rep needed for this level
-- @param currentRep The total amount of rep the player has.
function XToLevel.Lib:GetRepGainsToLevel(gain, lvlStart, lvlAmount, currentRep)
return math.ceil(((lvlStart + lvlAmount) - currentRep) / gain)
end
--- Calculates the number of rep gains needed to reach a specific rep "level".
-- @param gain The rep gained.
-- @param currentRep The total rep the player current has.
-- @param targetName The name of the target rep "level". If not valid, the function XToLevel.Lib:returns nil.
function XToLevel.Lib:GetRepGainsToTarget(gain, currentRep, targetName)
-- Get the lower limit and amount of the target level
local targetLower = nil
for index, value in ipairs(REP_LEVELS) do
if targetName == value[1] then
targetLower = value[2]
end
end
if not targetLower then
return nil
elseif gain > 0 and targetLower <= currentRep then
return nil
elseif gain < 0 and targetLower >= currentRep then
return nil
else
return math.ceil((targetLower - currentRep) / gain);
end
end
---
-- Returns the ID of the zone the player is currently in.
-- Borrowed from: https://www.wowinterface.com/forums/showpost.php?p=328804&postcount=4
-- /dump C_Map.GetMapInfo(C_Map.GetMapInfo(XToLevel.Lib:ZoneID())["parentMapID"])["name"]
---
function XToLevel.Lib:ZoneID()
local mapID = C_Map.GetBestMapForUnit("player")
if mapID then
local info = C_Map.GetMapInfo(mapID)
if info then
while info['mapType'] and info['mapType'] > 3 do
info = C_Map.GetMapInfo(info['parentMapID'])
end
return info['mapID']
end
end
return 1
end
---
-- Converts a classification between it's name and it's number. If you pass the
-- function a name, it will return and number, and the same in reverse.
-- If the input can not be converted, the function returns nil.
function XToLevel.Lib:ConvertClassification(classification)
if type(classification) == "number" and classification > 0 and classification <= # XToLevel.UNIT_CLASSIFICATIONS then
return XToLevel.UNIT_CLASSIFICATIONS[classification]
elseif type(classification) == "string" then
local out = nil
for i, v in ipairs(XToLevel.UNIT_CLASSIFICATIONS) do
if v == classification then
out = i
end
end
return out
end
return nil
end
---
-- Determines whether the player is eligable for the 3x Recriuit A Friend bonus.
---
function XToLevel.Lib:IsPlayerRafEligable()
local numPartyMembers = GetNumSubgroupMembers();
if numPartyMembers > 0 then
local memberID = 1;
while memberID <= numPartyMembers do
local member = "party" .. memberID;
if UnitInParty(member) then
if UnitIsVisible(member) and IsReferAFriendLinked(member) then
return true;
end
end
memberID = memberID + 1;
end
end
return false;
end
---
-- Determines whether the Recruit A Friend bonus should be applied.
---
function XToLevel.Lib:IsRafApplied()
return XToLevel.db.profile.general.rafEnabled and self:IsPlayerRafEligable();
end
---
-- Determines whether the player is currently inside a battleground zone.
---
function XToLevel.Lib:IsInBattleground()
local currentZone = GetRealZoneText()
for key, val in ipairs(XToLevel.BG_NAMES) do
if val == currentZone then
return true
end
end
return false
end
function XToLevel.Lib:ShowBattlegroundData()
return ((XToLevel.db.profile.ldb.tooltip.showBGInfo and XToLevel.Player.level >= 10) and (XToLevel.Player.level < XToLevel.Player.maxLevel or (# XToLevel.db.char.data.bgList) > 0))
end
function XToLevel.Lib:ShowDungeonData()
return ((XToLevel.db.profile.ldb.tooltip.showDungeonInfo) and (XToLevel.Player.level < XToLevel.Player.maxLevel or (# XToLevel.db.char.data.dungeonList) > 0))
end
---
-- Calculates the XP gained from killing a mob
-- First return value is the XP.
-- Second return value indicates if it's an "exact" value based on recorded data, or an "estimate" based on mob level.
---
function XToLevel.Lib:MobXP(mobName, mobLevel)
if type(mobName) ~= "string" then
mobName = nil
end
local charLevel = UnitLevel("player")
if type(mobLevel) ~= "number" then mobLevel = charLevel end
if mobName ~= nil then
for _, mobData in pairs(XToLevel.db.char.data.npcXP) do
if mobData.name == mobName and mobData.level == mobLevel then
return mobData.xp, "exact"
end
end
end
if mobLevel >= charLevel - 5 then
-- Standard base formula for all zones now. Previously the addition would vary.
local baseXP = (charLevel * 5) + 15
-- Mobs that are higher level than the player seem to always add 5% to the base
-- value, even at low level. (Slight variations at the lowest level, but not worth coding around now)
-- Mobs that are lower level seem to subtract 7% for each level at level 60 or higher. Levels
-- prior to that seem to increase that % on a gradient down to around 27% at level 1.
local levelDelta = mobLevel - charLevel
if levelDelta ~= 0 then
local modifier = 0.05 -- Default for higher levels
if not self:IsClassic() then
for _level, _deltas in ipairs(XToLevel.RETAIL_XP_MATRIX) do
for _d, _xp in pairs(_deltas) do
if _level == charLevel and tonumber(_d) == levelDelta then
return floor(_xp + 0.5), "exact"
end
end
end
if levelDelta < 0 then
for _, loop in ipairs(XToLevel.XP_MULTIPLIERS) do
if loop.level <= charLevel then
modifier = loop.modifier
else
break
end
end
end
else
-- So far, in Classic, I've observed a -20% per level below, and +5% per level above.
-- Will update as I level on Classic if that changes at high level.
if levelDelta < 0 then
-- XToLevel.XP_CLASSIC_ZERO_DIFFERENCE
for _, loop in ipairs(XToLevel.XP_CLASSIC_ZERO_DIFFERENCE) do
if loop.level <= charLevel then
modifier = 1/loop.divider
else
break
end
end
end
end
local multiplier = (modifier * levelDelta) + 1
return floor((baseXP * multiplier) + 0.5), "estimate"
else
return floor(baseXP + 0.5), "exact"
end
else
return 0, "exact"; -- Return 0 instead of for backwards compatibility. The function always returned a number back when it was a static formula.
end
end
---
-- Gets the gathering XP expected for a player at the given level.
function XToLevel.Lib:GatheringXP(playerLevel)
if type(playerLevel) ~= "number" then
playerLevel = UnitLevel("player")
end
local baseXP = XToLevel.GATHERING_XP[playerLevel]
-- TODO: Check if War Mode affects this
return baseXP
end
---
-- Gets the percent bonus received from heirloom items.
-- @return float Percentage as 0.0 to 1.0
local heirloom_slot_values = { [3] = 0.1, [5] = 0.1, [11] = 0.05, [12] = 0.05 }
function XToLevel.Lib:GetHeirloomXpBonus()
local sID, sQuality, sBlackhole;
local output = 0;
for slot, value in pairs(heirloom_slot_values) do
sID = GetInventoryItemID("player", slot)
if sID then
sBlackhole, sBlackhole, sQuality = GetItemInfo(sID)
if sQuality == 7 then
output = output + value
end
end
end
return output
end
function XToLevel.Lib:GetChatXPRegexp(isQuest)
local inInstance, itype = IsInInstance()
local inGroup = GetNumSubgroupMembers() > 0
local apiRegexp = nil
local isRested = GetXPExhaustion()
if not isQuest then
if inInstance and isRested then
if itype == "party" and inGroup then
apiRegexp = COMBATLOG_XPGAIN_EXHAUSTION1_GROUP
elseif itype == "raid" and inGroup then
apiRegexp = COMBATLOG_XPGAIN_EXHAUSTION1_RAID
else
apiRegexp = COMBATLOG_XPGAIN_EXHAUSTION1
end
elseif inInstance and not isRested then
if itype == "party" and inGroup then
apiRegexp = COMBATLOG_XPGAIN_FIRSTPERSON_GROUP
elseif itype == "raid" and inGroup then
apiRegexp = COMBATLOG_XPGAIN_FIRSTPERSON_RAID
else
apiRegexp = COMBATLOG_XPGAIN_FIRSTPERSON
end
else
if isRested then
apiRegexp = COMBATLOG_XPGAIN_EXHAUSTION1
else
apiRegexp = COMBATLOG_XPGAIN_FIRSTPERSON
end
end
else
-- Rested doesn't affect quests... daaa!!
apiRegexp = COMBATLOG_XPGAIN_FIRSTPERSON_UNNAMED
end
apiRegexp = string.gsub(apiRegexp, "%(", "%%(")
apiRegexp = string.gsub(apiRegexp, "%)", "%%)")
apiRegexp = string.gsub(apiRegexp, "%+", "%%+")
apiRegexp = string.gsub(apiRegexp, "%-", "%%-")
apiRegexp = string.gsub(apiRegexp, "%%%d?%$?s", "(.+)")
apiRegexp = string.gsub(apiRegexp, "%%%d?%$?d", "(%%d+)")
return apiRegexp
end
---
-- Extracts the XP amount from a chat XP gain message, as well as the mob name if
-- the message was generated by a kill, rather then a quest gain.
---
function XToLevel.Lib:ParseChatXPMessage(message, isQuest)
local pattern = XToLevel.Lib:GetChatXPRegexp(isQuest)
local mob, xp = strmatch(message, pattern);
-- If it is a quest, the XP will be return first and there will be no name. Swap them.
if tonumber(mob) then
xp = tonumber(mob)
mob = nil
end
if not tonumber(xp) then
xp = strmatch(message, "(%d+)")
-- Parsing has failed.
end
return xp, mob;
end
---
-- Rounds the input number to the given precision.
---
function XToLevel.Lib:round(input, precision, roundDown)
if input == nil then
return nil
end
if precision == nil then
precision = 0
end
precision = 10^(precision or 2)
local altered = input * precision
if roundDown then
return math.floor(altered) / precision
else
if altered - math.floor(altered) >= 0.5 then
return math.ceil(altered) / precision
else
return math.floor(altered) / precision
end
end
end
---
-- Formats the input number to a human-readable number. (Adds commas and periods)
---
function XToLevel.Lib:NumberFormat(input) -- /run XToLevel.Messages:Print(NumberFormat(127))
local strVersion = tostring(input)
local strLength = strlen(strVersion)
local numVersion = ""
local fraction = nil
local i = 0
while i < strLength do
i = i + 1
local current = strsub(strVersion, i, i)
if current == "." then
fraction = strsub(strVersion, i + 1)
break
else
numVersion = numVersion .. current
end
end
local output = ""
strLength = strlen(numVersion)
local i = 0
while i < strLength do
if i > 0 and mod(i, 3) == 0 then
output = "," .. output
end
output = strsub(numVersion, (strLength - i), (strLength - i)) .. output
i = i + 1
end
if fraction then
return output .. "." .. fraction
else
return output
end
end
---
-- Shrinks a number to a smaller format. (E.g. 1234000 = 1,23M)
---
local numberUnits = {"", "K", "M", "B"}
function XToLevel.Lib:ShrinkNumber(input)
input = tonumber(input)
if input < 100000 then
return XToLevel.Lib:NumberFormat(input)
else
-- local units = {"", "K", "M", "B"}
local index = 1
local output = input
while output > 1000 and index < # numberUnits do
output = output / 1000
index = index + 1
end
local precision = 2
if output < 10 then
precision = 2
elseif output < 100 then
precision = 1
else
precision = 0
end
return XToLevel.Lib:NumberFormat(tostring(XToLevel.Lib:round(output, precision, true))) .. numberUnits[index]
end
end
---
-- Converts a decimal (base 10) number to a hex (base 16) number.
---
function XToLevel.Lib:DecToHex(IN, minChars)
local B,K,OUT,I,D=16,"0123456789ABCDEF","",0
while IN>0 do
I=I+1
IN,D=math.floor(IN/B),mod(IN,B)+1
OUT=strsub(K,D,D)..OUT
if I > 1000 then
break
end
end
if minChars and tonumber(minChars) > 0 then
I = 0
while strlen(OUT) < tonumber(minChars) do
OUT = "0" .. OUT
if I > 1000 then
break
end
end
end
return OUT
end
---
-- Gets a color value to represent the given progress. (Green for 100%, red for 0%)
---
XToLevel.Lib.progressColor = { pro=0, hex=0, rgb={ r=0, g=0, b=0 } }
function XToLevel.Lib:GetProgressColor(pro)
if pro <= 0 then pro = 1 end -- 0 doesn't play well with the formulas. CBA to fix that so I just bypass it like so.
if pro > 100 then pro = 100 end
if self.progressColor.pro ~= pro then
local lh = pro <= 50 and true or false
self.progressColor.pro = pro
self.progressColor.rgb.r = math.floor((lh and 255) or (255 - (((pro - 50) / 50) * 255)))
self.progressColor.rgb.g = math.floor((lh and ((pro / 50) * 255)) or 255)
self.progressColor.rgb.b = 0
self.progressColor.hex = XToLevel.Lib:DecToHex(self.progressColor.rgb.r, 2) .. XToLevel.Lib:DecToHex(self.progressColor.rgb.g, 2) .. XToLevel.Lib:DecToHex(self.progressColor.rgb.b, 2)
end
return self.progressColor.hex, self.progressColor.rgb
end
XToLevel.Lib.progressColorS = { pro=0, proa=0, hex=0, rgb={ r=0, g=0, b=0 } } -- TODO: Complete and test
function XToLevel.Lib:GetProgressColor_Soft(progress)
local hex
local rgb = { r=0, g=0, b=0 }
local pro = tonumber(progress)
local proa = math.abs(progress-50)
rgb.r = math.floor((pro <= 66 and 255) or (255 - (153 * ((pro-66) / 34))))
rgb.g = math.floor((pro >= 50 and 255) or (255 - (153 * ((50-pro) / 50))))
rgb.b = math.floor((proa >= 16 and 102) or (102 * (proa / 16)))
hex = XToLevel.Lib:DecToHex(rgb.r, 2) .. XToLevel.Lib:DecToHex(rgb.g, 2) .. XToLevel.Lib:DecToHex(rgb.b, 2)
return hex, rgb
end
function XToLevel.Lib:GetDifficoultyColor(levelDifference)
end
---
-- Gets the minimum amount of XP that would be considered a valid BG objective reward.
---
function XToLevel.Lib:GetBGObjectiveMinXP()
if XToLevel.Player.level > 10 then
local bgMin = {
["Alterac Valley"] = 750,
["Isle of Conquest"] = 250,
["Strand of the Anchients"] = 500,
["Eye of the Storm"] = 500,
["Arathi Basin"] = 250,
["Warsong Gulch"] = 250,
}
local zone = GetRealZoneText()
local zoneMin = 500
for name, value in pairs(bgMin) do
if name == zone then
zoneMin = value
end
end
local playerMultiplier = (XToLevel.Player.level - 10) / (XToLevel.Player.maxLevel - 10)
return (XToLevel.Lib:round(zoneMin * playerMultiplier, 0))
else
return 0
end
end
---
-- Gets the appropriate tooltip anchor point for the give frame. (E.g. "TOPLEFT", "BOTTOMRIGHT")
---
function XToLevel.Lib:FindAnchor(frame)
local xcenter, ycenter = frame:GetCenter()
if not xcenter or not ycenter then
return "TOPLEFT", "BOTTOMLEFT"
end
local hor = (xcenter > UIParent:GetWidth() * 2 / 3) and "RIGHT" or (xcenter < UIParent:GetWidth() / 3) and "LEFT" or ""
local ver = (ycenter > UIParent:GetHeight() / 2) and "TOP" or "BOTTOM"
return ver..hor, frame, (ver == "BOTTOM" and "TOP" or "BOTTOM")..hor
end
function XToLevel.Lib:ReverseAnchor(anchor)
if string.find(anchor, "TOP") ~= nil then
anchor = string.gsub(anchor, "TOP", "BOTTOM")
else
anchor = string.gsub(anchor, "BOTTOM", "TOP")
end
if string.find(anchor, "LEFT") ~= nil then
anchor = string.gsub(anchor, "LEFT", "RIGHT")
else
anchor = string.gsub(anchor, "RIGHT", "LEFT")
end
return anchor
end
---
-- Splits the str on the delim char, maxNb number of times.
-- http://lua-users.org/wiki/SplitJoin
---
function XToLevel.Lib:Split(str, delim, maxNb)
-- Eliminate bad cases...
--if string.find(str, delim) == nil then
-- return { str }
--end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gmatch(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
if # result == 0 then
result[1] = str;
end
return result
end
---
-- Formats a timestamp into a human-readable Date-Time string
-- following a "5d 12h 36m 48s" format.
function XToLevel.Lib:TimeFormat(timestamp)
if type(timestamp) == "number" and timestamp > 0 then
local day = floor(timestamp / 86400)
local hour = floor((timestamp - (day * 86400)) / 3600)
local minute = floor((timestamp - (day * 86400) - (hour * 3600)) / 60)
local second = floor(mod(timestamp, 60))
if day < 0 then
return "NaN"
else
local output = ""
if day > 0 then
output = day .. "d "
end
if hour > 0 or output ~= "" then
output = output .. hour .. "h "
end
if minute > 0 or output ~= "" then
output = output .. minute .. "m "
end
if second > 0 or output ~= "" then
output = output .. second .. "s"
end
return output
end
else
return "NaN"
end
end