-
Notifications
You must be signed in to change notification settings - Fork 3
/
funx.lua
4704 lines (3861 loc) · 124 KB
/
funx.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
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
-- funx.lua
--
-- Version 0.2
--
-- Copyright (C) 2010 David I. Gross. All Rights Reserved.
--
-- This software is is protected by the author's copyright, and may not be used, copied,
-- modified, merged, published, distributed, sublicensed, and/or sold, without
-- written permission of the author.
--
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
--
-- ===================
-- USEFUL FUNCTIONS.
-- ===================
local FUNX = {}
-- Requires json library
local json = require ( "json" )
local lfs = require ( "lfs" )
local widget = require ("widget")
-- Used by tellUser...the handler for the timed message
local timedMessage = nil
local timedMessageList = {}
-- Make a local copy of the application settings global
local screenW, screenH = display.contentWidth, display.contentHeight
local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight
local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight
local midscreenX = screenW*(0.5)
local midscreenY = screenH*(0.5)
-- functions
local floor = math.floor
local min = math.min
local max = math.max
local random = math.random
local match = string.match
local gmatch = string.gmatch
local find = string.find
local gfind = string.gfind
-- ALPHA VALUES, can change for RGB or HDR systems
local OPAQUE = 255
local TRANSPARENT = 0
-- -------------------------------------------------------------
-- GRAPHICS 2.0 POSITIONING
-- ------------------------------------------------------------
-----------
-- Shortcut to set x,y to 0,0
local function toZero(o)
o.x, o.y = 0,0
end
-----------
-- Shortcut to set anchors to top-left
local function anchorTopLeft(o)
o.anchorX, o.anchorY = 0,0
end
-----------
-- Shortcut to set anchors to top-left
local function anchorCenter(o)
o.anchorX, o.anchorY = 0.5, 0.5
end
-----------
-- Shortcut to set anchors to top-left and x,y to 0,0
local function anchorTopLeftZero(o)
o.anchorX, o.anchorY = 0,0
o.x, o.y = 0,0
end
-----------
-- Shortcut to set anchors to center and x,y to 0,0
local function anchorCenterZero(o)
o.anchorX, o.anchorY = 0.5, 0.5
o.x, o.y = 0,0
end
-----------
-- Shortcut to set anchors to top-left and x,y to 0,0
local function anchorBottomRightZero(o)
o.anchorX, o.anchorY = 1,1
o.x, o.y = 0,0
end
-- Add an invisible positioning rectangle for a group
local function addPosRect(g, vis, c)
local r = display.newRect(g, 0,0,10,10)
r.isVisible = vis
c = c or {250,0,0,100}
r:setFillColor(unpack(c))
anchorTopLeftZero(r)
return g
end
local function centerInParent(g)
anchorCenter(g)
g.x = g.parent.width/2
g.y = g.parent.height/2
return g
end
-- ------------------------------------------------------------
-- Get index in system table of a system directory
-- ------------------------------------------------------------
local function indexOfSystemDirectory( systemPath )
local i = ""
if (systemPath == system.DocumentsDirectory) then
i = "DocumentsDirectory"
elseif (systemPath == system.ResourceDirectory) then
i = "ResourceDirectory"
elseif (systemPath == system.CachesDirectory) then
i = "CachesDirectory"
end
return i
end
-- ------------------------------------------------------------
-- DEBUGGING Timer
-- ------------------------------------------------------------
local firstTime = system.getTimer()
local lastTimePassed = system.getTimer()
local function timePassed(msg)
local t2 = system.getTimer()
local t = t2 - lastTimePassed
lastTimePassed = t2
msg = msg or ""
print ("funx.timePassed: ", math.floor(t) .. "ms", msg) --, "Total:", math.floor(t2-firstTime))
io.flush( )
end
-----------------
-- 'n' is the call stack level to show
-- '2' will show the calling function
local function printFuncName(n)
n = n or 2
local info = debug.getinfo(n, "Snl")
if info.what == "C" then -- is a C function?
print(n, "C function")
else -- a Lua function
print(string.format("[%s]:%d", info.name, info.currentline))
end
end
local function isTable(t)
return (type(t) == "table")
end
-----------------
local function traceback ()
print ("FUNX.TRACEBACK:")
local level = 1
while true do
local info = debug.getinfo(level, "Sl")
if not info then break end
if info.what == "C" then -- is a C function?
print(level, "C function")
else -- a Lua function
print(string.format("[%s]:%d",
info.short_src, info.currentline))
end
level = level + 1
end
end
-----------------
-- Fails for negatives, apparently
local function round2(num, idp)
local mult = 10^(idp or 0)
return floor(num * mult + 0.5) / mult
end
local function round(num, idp)
return tonumber(string.format("%." .. (idp or 0) .. "f", num))
end
-----------------
-- Given a value from an XML element, it could be x=y or x.value=y
-- Return y in either case.
-- If asNil is true, then if the value is "" or nil, return nil
local function getValue(x,asNil)
local r
if (type(x) == "table") then
if (x.value) then
r = x.value
elseif (x.Attributes and x.Attributes.value) then
r = x.Attributes.value
elseif (x._attr and x._attr.value) then
r = x._attr.value
end
else
r = x
end
if (asNil and (r == "" or r == nil or r == false)) then
r = nil
end
return r
end
--------------
-- unescape/escape a hex string
local function unescape (s)
if (not s) then
return ""
end
s = string.gsub(s, "+", " ")
s = string.gsub(s, "%%(%x%x)", function (h)
return string.char(tonumber(h, 16))
end)
return s
end
local function escape(s)
s = string.gsub(s, "([&=+%c])", function(c)return string.format("%%%02X", string.byte(c))end)
s = string.gsub(s, " ", "+")
return s
end
--=========
--- Remove a value from a table. The table is searched and the value removed from it.
local function removeFromTable(t,obj)
for i,o in pairs(t) do
if (o == obj) then
t[i] = nil
print ("removeFromTable: removed item #" .. i)
return true
end
end
return false
end
-----------------
-- Table is empty?
local function tableIsEmpty(t)
if (t and type(t) == "table" ) then
if (next(t) == nil) then
return true
end
end
return false
end
-----------------
-- Length of a table, i.e. number elements in it.
local function tablelength (t)
if (type(t) ~= "table") then
return 0
end
local count = 0
for _, _ in pairs(t) do
count = count + 1
end
return count
end
-- Delete fields of the form {{x}} in the string s
local function removeFields (s)
if (not s) then return nil end
local r = gfind(s,"%{%{.-%}%}")
local res = s
for w in r do
res = trim(string.gsub(res, w, ""))
end
return res
end
-- Delete fields of the form {x} in the string s
local function removeFieldsSingle (s)
if (not s) then return nil end
local r = gfind(s,"%b{}")
local res = s
for w in r do
res = trim(string.gsub(res, w, ""))
end
return res
end
--===========
--- Escape keys in tables so the key name can be used in a gsub search/replace
-- @param t Table with keys that might need escaping
-- @return res Key:value pairs: original key => clean key
-- e.g. { "icon-1" = "myicon.jpg" } ===> { "icon-1" = "icon%-1" }
local function getEscapedKeysForGsub(t)
local gsub = string.gsub
-- Chars to escape: ( ) . % + - * ? [ ^ $
local res = {}
for i,v in pairs(t) do
res[i] = gsub(i, "([%(%)%.%%%+%-%*%?%[%^%$])", "%%%1")
end
return res
end
--- Substitute for {{x}} with table.x from a table.
-- There can be multiple fields in the string, s.
-- Returns the string with the fields filled in.
-- @param s String with codes to replace
-- @param t Table of key:value pairs to use for replacement (search for key)
-- @param escapeTheKeys if TRUE then escape the keys of the subsitutions table (t), if a table then use that table as the escaped keys table
-- @return s string with replacements
local function substitutions (s, t, escapeTheKeys)
local gsub = string.gsub
if (not s or not t or t=={}) then
--print ("funx.substitutions: No Values passed!")
return s
end
local tclean = {}
if (escapeTheKeys) then
if (type(escapeTheKeys) == "table") then
tclean = escapeTheKeys
else
tclean = getEscapedKeysForGsub(t)
end
end
local r = gfind(s,"%{%{(.-)%}%}")
for w in r do
local searchTerm = tclean[w] or w
if (t[w]) then
s = gsub(s, "{{"..searchTerm.."}}", t[w])
--print ("{{"..searchTerm.."}}", t[w],s)
end
end
return s
end
-- Substitute for {x} with table.x from a table.
-- There can be multiple fields in the string, s.
-- Returns the string with the fields filled in.
local function OLD_substitutionsSLOWER (s, t)
if (not s or not t or t=={}) then
--print ("funx.substitutions: No Values passed!")
return s
end
--local r = gfind(s,"%b{}")
local r = gfind(s,"%{%{.-%}%}")
local res = s
for w in r do
local i,j = string.find(w, "%{%{(.-)%}%}")
local k = string.sub(w,i+2,j-2)
if (t[k]) then
res = string.gsub(res, w, t[k])
end
--print ("substitutions for in "..res.." for {{"..k.."}} with ",t[k], "RESULT:",res)
end
return res
end
--===========
--- Replace all substitutions in the entire table, including
-- nested tables.
-- @param t Table in which to substitute
-- @param subs table Table of substitutions
local function tableSubstitutions(t, subs, escapeTheKeys)
if (type(t) ~= "table") then
return t
end
if (type(subs) ~= "table" or not subs or subs == {} ) then
return t
end
if (escapeTheKeys) then
if (type(escapeTheKeys) == "table") then
tclean = escapeTheKeys
else
tclean = getEscapedKeysForGsub(subs)
end
end
for i,element in pairs(t) do
if (i ~= "screen") then
if (type(element) == "string") then
t[i] = substitutions (element, subs, tclean)
--print ("element:", element, t[i])
elseif (type(element) == "table") then
tableSubstitutions( t[i], subs, tclean)
elseif (element == "[[null]]" or element == "[[NULL]]" ) then
t[i] = nil
end
end
end
end
--===========
--- Remove elements that contain unresolved {{}} codes.
-- @param t Table in which to substitute
local function tableRemoveUnusedCodedElements(t )
if (type(t) ~= "table") then
return t
end
for i,element in pairs(t) do
if (i ~= "screen") then
if (type(element) == "string" and string.find(element, "%{%{.-%}%}")) then
--print ("tableRemoveUnusedCodedElements: Remove ", t[i])
t[i] = ""
elseif (type(element) == "table") then
tableRemoveUnusedCodedElements( t[i] )
end
end
end
end
-- hasFieldCodes(s)
-- Return true/false if the string has field codes, i.e. {x} inside it
local function hasFieldCodes(s)
if (type(s) ~= "string") then
return false
end
s = s or ""
local r = string.find(s,"%{%{.-%}%}")
if (r) then
return true
else
return false
end
end
-- hasFieldCodes(s)
-- Return true/false if the string has field codes, i.e. {x} inside it
local function hasFieldCodesSingle(s)
if (type(s) ~= "string") then
return false
end
s = s or ""
local r = string.find(s,"%b{}")
if (r) then
return true
else
return false
end
end
-- Get element name from string.
-- If the string is {{xxx}} then the field name is "xxx"
local function getElementName (s)
local r = gfind(s,"%{%{(.-)%}%}")
local res = "RESULT: "..s
for w in r do
print ("extracted ",w)
break
end
return w
end
-- Dump an XML table
local function dump(_class, no_func, depth)
if (not _class) then
print ("dump: not a class.");
return;
end
if(depth==nil) then depth=0; end
local str="";
for n=0,depth,1 do
str=str.."\t";
end
if (depth > 10) then
print ("Oops, running away! Depth is "..depth)
return
end
print (str.."["..type(_class).."]");
print (str.."{");
if (type(_class) == "table") then
for i,field in pairs(_class) do
if(type(field)=="table") then
local fn = tostring(i)
if (string.sub(fn,1,2) == "__") then
print (str.."\t"..tostring(i).." = (not expanding this internal table)");
else
print (str.."\t"..tostring(i).." =");
dump(field, no_func, depth+1);
end
else
if(type(field)=="number") then
print (str.."\t"..tostring(i).."="..field);
elseif(type(field) == "string") then
print (str.."\t"..tostring(i).."=".."\""..field.."\"");
elseif(type(field) == "boolean") then
print (str.."\t"..tostring(i).."=".."\""..tostring(field).."\"");
else
if(not no_func)then
if(type(field)=="function")then
print (str.."\t"..tostring(i).."()");
else
print (str.."\t"..tostring(i).."<userdata=["..type(field).."]>");
end
end
end
end
end
end
print (str.."}");
end
--------------------------------------------------------
-- tableCopy
local function tableCopy(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, _copy(getmetatable(object)))
end
return _copy(object)
end
--------------------------------------------------------
-- Trim
-- Remove white space from a string, OR table of strings
-- recursively
-- Only act on strings
-- If flag set, return nil for an empty string
local function trim(s, returnNil)
if (s) then
if (type(s) == "table") then
for i,v in ipairs(s) do
s[i] = trim(v, returnNil)
end
elseif (type(s) == "string") then
s = s:gsub("^%s*(.-)%s*$", "%1")
end
end
if (returnNil and s == "") then
return nil
end
return s
end
--------------------------------------------------------
-- ltrim
-- Remove white space from the start of a string, OR table of strings recursively
-- Only act on strings
-- If flag set, return nil for an empty string
local function ltrim(s, returnNil)
if (s) then
if (type(s) == "table") then
for i,v in ipairs(s) do
s[i] = ltrim(v, returnNil)
end
elseif (type(s) == "string") then
s = s:gsub("^%s*(.-)", "%1")
end
end
if (returnNil and s == "") then
return nil
end
return s
end
--------------------------------------------------------
-- rtrim
-- Remove white space from the end of a string, OR table of strings recursively
-- Only act on strings
-- If flag set, return nil for an empty string
local function rtrim(s, returnNil)
if (s) then
if (type(s) == "table") then
for i,v in ipairs(s) do
s[i] = rtrim(v, returnNil)
end
elseif (type(s) == "string") then
s = s:gsub("(.-)%s*$", "%1")
end
end
if (returnNil and s == "") then
return nil
end
return s
end
--------------------------------------------------------
-- table merge
-- Overwrite elements in the first table with the second table!
local function tableMerge(t1, t2)
if (type(t1) ~= "table") then
return t2
end
if (type(t2) ~= "table") then
return t1
end
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
tableMerge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
local function split(str, pat, doTrim)
pat = pat or ","
if (not str) then
return nil
end
str = tostring(str)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
if doTrim then cap = trim(cap) end
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
if doTrim then cap = trim(cap) end
table.insert(t,cap)
end
return t
end
-------------------------------------------------
--- GET DEVICE SCALE FACTOR FOR RETINA RESIZING
--1 = no need to change anything
--2 = multiply by 2
-- examples:
-- local scalingRatio = scaleFactorForRetina()
-- local scalesuffix = "@"..scalingRatio.."x"
--
-- local scalingRatio = 1/scaleFactorForRetina()
-- width = width/scalingRatio
-- height = height/scalingRatio
-------------------------------------------------
local function scaleFactorForRetina()
local deviceWidth = ( display.contentWidth - (display.screenOriginX * 2) ) / display.contentScaleX
local scaleFactor = math.floor( deviceWidth / display.contentWidth )
return scaleFactor
end
-------------------------------------------------
-- CHECK IMAGE DIMENSION & SCALE ACCORDINGLY
-------------------------------------------------
local function checkScale(p)
if p.width > viewableScreenW or p.height > viewableScreenH then
if p.width/viewableScreenW > p.height/viewableScreenH then
p.xScale = viewableScreenW/p.width
p.yScale = viewableScreenW/p.width
else
p.xScale = viewableScreenH/p.height
p.yScale = viewableScreenH/p.height
end
end
end
-------------------------------------------------
-- RESCALE AN IMAGE THAT WAS DESIGNED FOR THE IPAD (1024X768) FOR THE CURRENT PLATFORM
-- Assuming the graphic was made for a different platform
-- this resizes it
-------------------------------------------------
local function resizeFromIpad(p)
local currentR = viewableScreenW/viewableScreenH
local ipadR = 1024/768
local r
if (currentR > ipadR) then
-- use ration based on different heights
r = viewableScreenH / 768
else
r = viewableScreenW / 1024
end
if (r ~= 1) then
p:scale(r,r)
--print ("Resize image by (viewableScreenW/1024) = "..r)
end
end
-------------------------------------------------
-- RESCALE COORDINATES THAT WERE DESIGNED FOR THE IPAD (1024X768) FOR THE CURRENT PLATFORM
-- Used to reposition coordinates that were set up for the iPad, e.g. x,y positions
-- If the screen is a different shape, pad the x to make up for it
-- iPad is 1024/768 = 133/100 (1.33)
-- CONVERT results to integer (math.floor)
local function rescaleFromIpad(x,y)
-- Do nothing if this is an iPad screen!
if ( (screenW == 1024 and screenH == 768) or (screenW == 768 and screenH == 1024) )then
return x,y
end
if (x == nil) then
return 0,0
end
--print ("viewableScreenW="..viewableScreenW..", viewableScreenH="..viewableScreenH)
local currentR = viewableScreenW/viewableScreenH
local ipadR = 1024/768
local fixedH = 768
local fixedW = 1024
if (currentR > 1) then
ipadR = 1/ipadR
fixedH = 1024
fixedW = 768
end
local r
if (currentR > ipadR) then
-- use ration based on different heights
r = viewableScreenH / fixedH
else
r = viewableScreenW / fixedW
end
-- Pad for different shape
local screenR = floor((viewableScreenW / viewableScreenH) * 100 )/100
local px = 0
--print ("screenR="..screenR)
if (y and (screenR ~= floor((ipadR)*100)/100)) then
px = floor((viewableScreenW - (viewableScreenH * ipadR))/2)
end
x = floor((x * r) + (px))
--print ("Padding x="..px)
if (y ~= nil) then
y = floor(y * r)
return x,y
else
return x
end
end
-- If the value is a percentage, multiply by the 2nd param, else return the 1st param
-- value is rounded to nearest integer, UNLESS the 2nd param is less than 1
-- or noRound = true
-- If x is nil, but y is not, then return the y (i.e. assume 100%)
local function applyPercent (x,y,noRound)
if (x == nil and y == nil) then
return nil
end
if (x == nil and y ~= nil) then
return tonumber(y)
end
x = x or 0
y = y or 0
local v = string.match(trim(x), "(.+)%%$")
if v then
v = (v / 100) * y
if ((not noRound) and (y>1)) then
v = math.floor(v+0.5)
end
else
v = x
end
return tonumber(v)
end
-- ===========
--- Get a percentage of the screen height
-- @param y
-- @param noRound If false, value NOT rounded to nearest integer
local function percentOfScreenHeight (y,noRound)
return applyPercent (y, screenH, noRound)
end
-- ===========
--- Get a percentage of the screen height
-- @param y
-- @param noRound If false, value NOT rounded to nearest integer
local function percentOfScreenWidth (x,noRound)
return applyPercent (x, screenW, noRound)
end
--------------------------------------------------------
-- File Exists
-- default directory is system.ResourceDirectory
-- not system.DocumentsDirectory
--------------------------------------------------------
local function fileExists(f,d)
if (f) then
d = d or system.ResourceDirectory
local filePath = system.pathForFile( f, d )
local exists = false
-- Determine if file exists
if (filePath ~= nil) then
local fileHandle = io.open( filePath, "r" )
if (fileHandle) then -- nil if no file found
exists = true
io.close(fileHandle)
else
--print ("WARNING: Missing file: ",tostring(filePath))
end
end
return (exists)
else
--print ("WARNING: Missing file: ",tostring(filePath))
return false
end
end
------------------------------------------------------------------------
-- Save table, load table, default from documents directory
------------------------------------------------------------------------
----------------------
-- Save/load functions
local function saveData(filePath, text)
--local levelseq = table.concat( levelArray, "-" )
local file = io.open( filePath, "w" )
if (file) then
file:write( text )
io.close( file )
return true
else
print ("Error: funx.saveData: Could not create file "..tostring(filePath))
return false
end
end
local function loadData(filePath)
local t = nil
--local levelseq = table.concat( levelArray, "-" )
local file = io.open( filePath, "r" )
if (file) then
t = file:read( "*a" )
io.close( file )
else
print ("funx.loadData: No file found at "..tostring(filePath))
end
return t
end
local function saveTableToFile(filePath, dataTable)
--local levelseq = table.concat( levelArray, "-" )
file = io.open( filePath, "w" )
for k,v in pairs( dataTable ) do
file:write( k .. "=" .. v .. "," )
end
io.close( file )
end
-- Load a table form a text file.
-- The table is stored as comma-separated name=value pairs.
local function loadTableFromFile(filePath, s)
local substring = string.sub
if (not filePath) then
print ("WARNING: loadTableFromFile: Missing file name.")
return false
end
local file = io.open( filePath, "r" )
-- separator, default is comma
s = s or ","
if file then
-- Read file contents into a string
local dataStr = file:read( "*a" )
-- Break string into separate variables and construct new table from resulting data
local datavars = split(dataStr, s)
local dataTableNew = {}
for i = 1, #datavars do
local firstchar = substring(trim(datavars[i]),1,1)
-- split each name/value pair
if ( not ((firstchar == "#") or (firstchar == "/") or (firstchar == "-") ) ) then
local onevalue = trim(split(datavars[i], "="))
if (onevalue[1]) then
dataTableNew[onevalue[1]] = onevalue[2]
end
end
end
io.close( file ) -- important!
-- Note: all values arrive as strings; cast to numbers where numbers are expected
dataTableNew["randomValue"] = tonumber(dataTableNew["randomValue"])
return dataTableNew
else
print ("WARNING: loadTableFromFile: File not found ("..filePath..")")
return false
end
end
local function saveTable(t, filename, path)
if (not t or not filename) then
return true
end
path = path or system.DocumentsDirectory
--print ("funx.saveTable: save to "..filename)
local json = json.encode (t)
local filePath = system.pathForFile( filename, path )
return saveData(filePath, json)
end
local function loadTable(filename, path)
path = path or system.DocumentsDirectory
if (fileExists(filename,path)) then
local filePath = system.pathForFile( filename, path )
--print ("funx.loadTable: load from "..filePath)
local t = {}