-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSMW-BizHawk.lua
6496 lines (5349 loc) · 281 KB
/
SMW-BizHawk.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
--##################################################################################
--## ##
--## Super Mario World (any version) Utility Script for BizHawk ##
--## http://tasvideos.org/Bizhawk.html ##
--## ##
--## Authors: Bruno Valadão Cunha (BrunoValads) [9 april 2018 ~ today] ##
--## Rodrigo A. do Amaral (Amaraticando) [15 july 2014 ~ 8 april 2018] ##
--## ##
--## Git repository: https://github.com/brunovalads/smw-stuff ##
--## ##
--##################################################################################
--#############################################################################
-- CONFIG (YOU PROBABLY WANT TO EDIT THE SMW-BizHawk-config.ini FILE INSTEAD OF THIS)
local config = {}
config.ini_filename = "SMW-BizHawk-config.ini"
config.ini_filepath = "./" .. config.ini_filename -- relative to the folder of the script
config.DEFAULT_OPTIONS = {
--- Hotkeys (look at the manual to see all the valid keynames)
-- make sure that the hotkeys below don't conflict with previous bindings
hotkey_increase_opacity = "equals", -- to increase the opacity of the text: the '='/'+' key
hotkey_decrease_opacity = "minus", -- to decrease the opacity of the text: the '-'/'_' key
--- Show/hide options
-- Player
display_player_info = true,
display_player_main_info = true,
display_yoshi_info = true,
display_player_hitbox = true,
display_player_block_interaction = true,
display_cape_hitbox = true,
display_camera_region = false,
display_debug_player_extra = false,
-- Sprites
display_sprite_info = true,
display_sprite_main_table = true,
display_sprite_hitbox = true,
display_sprite_vs_sprite_hitbox = false,
display_sprite_spawning_areas = true,
display_sprite_vanish_area = true,
display_misc_sprite_table = {
[1] = false, [2] = false, [3] = false, [4] = true, [5] = false, [6] = false, [7] = false,
[8] = false, [9] = false, [10] = false, [11] = false, [12] = true, [13] = true, [14] = true,
[15] = true, [16] = true, [17] = true, [18] = true, [19] = true, [20] = true, [21] = true,
[22] = true, [23] = true, [24] = true, [25] = false, [26] = true, [27] = false, [28] = false,
[29] = true, [30] = false, [31] = false, [32] = false, [33] = true, [34] = true, [35] = false,
[36] = false, [37] = false, [38] = true, [39] = false, [40] = false, [41] = false, [42] = false,
[43] = false, [44] = false, [45] = false, [46] = true, [47] = false, [48] = false, [49] = false
},
display_debug_sprite_tweakers = false,
display_debug_sprite_extra = false,
-- General
display_game_info = true,
display_movie_info = true,
display_counters = true,
display_overworld_info = true,
use_block_duplication_predictor = true,
display_RNG_info = false,
display_controller_data = false,
display_lagmeter = true,
-- Other sprites
display_other_sprites_info = true,
display_extended_sprite_info = true,
display_cluster_sprite_info = true,
display_minor_extended_sprite_info = false,
display_bounce_sprite_info = false,
display_quake_sprite_info = false,
display_debug_extended_sprite = false,
display_debug_cluster_sprite = false,
display_debug_minor_extended_sprite = false,
display_debug_bounce_sprite = false,
-- Level
display_level_info = true,
display_level_main_info = true,
display_level_boundary = false,
display_sprite_data = true,
display_sprite_load_status = true,
display_screen_info = false,
display_exit_info = true,
-- Script settings
draw_tiles_with_click = true,
max_tiles_drawn = 20, -- the max number of tiles to be drawn/registered by the script
display_mouse_coordinates = true,
left_gap = 8*(12 + 6),
right_gap = (36*10/2)+2, -- (36 maximum chars of the sprite info)*(10 pixels of BizHawk font width)/(2, the scale)+(2 to make it fit better)
top_gap = 20,
bottom_gap = 50,
positions_in_hex = true,
speeds_in_hex = true,
}
-- Colour settings
config.DEFAULT_COLOUR = {
-- Text
default_text_opacity = 1.0,
default_bg_opacity = 0.4,
text = "#ffffffff",
background = "#000000ff",
outline = "#000040ff",
warning = "#ff0000ff",
warning_bg = "#0000ffff",
warning2 = "#ff00ffff",
positive = "#00ff00ff",
positive2 = "#00ffffff",
weak = "#a9a9a9ff",
very_weak = "#ffffff60",
disabled = "#808080ff",
joystick_input = "#ffff00ff",
joystick_input_bg = "#ffffff30",
button_text = "#300030ff",
mainmenu_outline = "#ffffffc0",
mainmenu_bg = "#000000c0",
-- Counters
counter_pipe = "#00ff00ff",
counter_multicoin = "#ffff00ff",
counter_gray_pow = "#a5a5a5ff",
counter_blue_pow = "#4242deff",
counter_dircoin = "#8c5a19ff",
counter_pballoon = "#f8d870ff",
counter_star = "#ffd773ff",
counter_fireflower = "#ff8c00ff",
-- hitbox and related text
mario = "#ff0000ff",
mario_bg = "#00000000",
mario_mounted_bg = "#00000000",
interaction = "#ffffffff",
interaction_bg = "#00000020",
interaction_nohitbox = "#000000a0",
interaction_nohitbox_bg = "#00000070",
mario_oam_hitbox = "#00ff80ff",
cape = "#ffd700ff",
cape_bg = "#ffd70060",
-- Sprites
sprites = {
0xff80FFFF, -- cyan
0xffA0A0FF, -- blue
0xffFF6060, -- red
0xffFF80FF, -- magenta
0xffFFA100, -- orange
0xffFFFF80, -- yellow
0xff40FF40 -- green
},
sprites_interaction_pts = "#ffffffff",
sprites_bg = "#0000b070",
sprites_clipping_bg = "#000000a0",
sprites_faint = "#00000010",
sprite_vision_active = "#d00000ff",
sprite_vision_active_bg = "#d0000020",
sprite_vision_passive = "#00d0d0c0",
extended_sprites = "#ff8000ff",
extended_sprites_bg = "#00ff0050",
special_extended_sprite_bg = "#00ff0060",
goal_tape_bg = "#ffff0050",
fireball = "#b0d0ffff",
baseball = "#0040a0ff",
cluster_sprites = "#ff80a0ff",
sumo_brother_flame = "#0040a0ff",
minor_extended_sprites = "#ff90b0ff",
quake_sprite = "#00d0d0d0",
quake_sprite_bg = "#d0000020",
awkward_hitbox = "#204060ff",
awkward_hitbox_bg = "#ff800060",
-- Yoshi
yoshi = "#00ffffff",
yoshi_bg = "#00ffff40",
yoshi_mounted_bg = "#00000000",
tongue_line = "#ffa000ff",
tongue_bg = "#00000060",
-- Level related
block = "#00008bff",
blank_tile = "#ffffff70",
block_bg = "#22cc88a0",
layer2_line = "#ff2060ff",
layer2_bg = "#ff206040",
camera_region = "#40002040",
screen_borders = "#0000FF80",
}
-- Input key names
local INPUT_KEYNAMES = { -- BizHawk
A=false, Add=false, Alt=false, Apps=false, Attn=false, B=false, Back=false, BrowserBack=false, BrowserFavorites=false,
BrowserForward=false, BrowserHome=false, BrowserRefresh=false, BrowserSearch=false, BrowserStop=false, C=false,
Cancel=false, Capital=false, CapsLock=false, Clear=false, Control=false, ControlKey=false, Crsel=false, D=false, D0=false,
D1=false, D2=false, D3=false, D4=false, D5=false, D6=false, D7=false, D8=false, D9=false, Decimal=false, Delete=false,
Divide=false, Down=false, E=false, End=false, Enter=false, EraseEof=false, Escape=false, Execute=false, Exsel=false,
F=false, F1=false, F10=false, F11=false, F12=false, F13=false, F14=false, F15=false, F16=false, F17=false, F18=false,
F19=false, F2=false, F20=false, F21=false, F22=false, F23=false, F24=false, F3=false, F4=false, F5=false, F6=false,
F7=false, F8=false, F9=false, FinalMode=false, G=false, H=false, HanguelMode=false, HangulMode=false, HanjaMode=false,
Help=false, Home=false, I=false, IMEAccept=false, IMEAceept=false, IMEConvert=false, IMEModeChange=false,
IMENonconvert=false, Insert=false, J=false, JunjaMode=false, K=false, KanaMode=false, KanjiMode=false, KeyCode=false,
L=false, LaunchApplication1=false, LaunchApplication2=false, LaunchMail=false, LButton=false, LControlKey=false,
Left=false, LineFeed=false, LMenu=false, LShiftKey=false, LWin=false, M=false, MButton=false, MediaNextTrack=false,
MediaPlayPause=false, MediaPreviousTrack=false, MediaStop=false, Menu=false, Modifiers=false, Multiply=false, N=false,
Next=false, NoName=false, None=false, NumLock=false, NumPad0=false, NumPad1=false, NumPad2=false, NumPad3=false,
NumPad4=false, NumPad5=false, NumPad6=false, NumPad7=false, NumPad8=false, NumPad9=false, O=false, Oem1=false,
Oem102=false, Oem2=false, Oem3=false, Oem4=false, Oem5=false, Oem6=false, Oem7=false, Oem8=false, OemBackslash=false,
OemClear=false, OemCloseBrackets=false, Oemcomma=false, OemMinus=false, OemOpenBrackets=false, OemPeriod=false,
OemPipe=false, Oemplus=false, OemQuestion=false, OemQuotes=false, OemSemicolon=false, Oemtilde=false, P=false, Pa1=false,
Packet=false, PageDown=false, PageUp=false, Pause=false, Play=false, Print=false, PrintScreen=false, Prior=false,
ProcessKey=false, Q=false, R=false, RButton=false, RControlKey=false, Return=false, Right=false, RMenu=false, RShiftKey=false,
RWin=false, S=false, Scroll=false, Select=false, SelectMedia=false, Separator=false, Shift=false, ShiftKey=false,
Sleep=false, Snapshot=false, Space=false, Subtract=false, T=false, Tab=false, U=false, Up=false, V=false, VolumeDown=false,
VolumeMute=false, VolumeUp=false, W=false, X=false, XButton1=false, XButton2=false, Y=false, Z=false, Zoom=false
}
--#############################################################################
-- INITIAL STATEMENTS
-- Load environment
package.path = "bizhawk/scripts/lib/?.lua" .. ";" .. package.path
local gui, input, joypad, emu, movie, memory, mainmemory, bit = gui, input, joypad, emu, movie, memory, mainmemory, bit
local unpack = unpack or table.unpack
local string, math, table, next, ipairs, pairs, io, os, type = string, math, table, next, ipairs, pairs, io, os, type
local fmt = string.format
local floor = math.floor
local NTSC_FRAMERATE = 60.0988138974405
local PAL_FRAMERATE = 50.0069789081886
--############################################################################
-- MODULES (now unmodularized)
--&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
--&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
-- LUAP: General purpose lua extension
local luap = {}
function luap.get_emulator_name()
if lsnes_features then return "lsnes"
elseif bizstring then return "BizHawk"
elseif snes9x then return "Snes9x"
else return nil
end
end
function luap.file_exists(name)
local f = io.open(name, "r")
if f ~= nil then io.close(f) return true else return false end
end
function luap.unrequire(mod)
package.loaded[mod] = nil
_G[mod] = nil
end
local function copytable(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[copytable(orig_key)] = copytable(orig_value) -- possible stack overflow
end
setmetatable(copy, copytable(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
luap.copytable = copytable
local function mergetable(source, t2)
for key, value in pairs(t2) do
if type(value) == "table" then
if type(source[key] or false) == "table" then
mergetable(source[key] or {}, t2[key] or {}) -- possible stack overflow
else
source[key] = value
end
else
source[key] = value
end
end
return source
end
luap.mergetable = mergetable
-- Creates a set from a list
function luap.make_set(list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
-- Sum of the digits of a integer
function luap.sum_digits(number)
local sum = 0
while number > 0 do
sum = sum + number%10
number = floor(number*0.1)
end
return sum
end
-- Returns the exact chosen digit of a number from the left to the right or from the right to the left, in a given base
-- E.g.: read_digit(654321, 2, 10, "left to right") -> 5; read_digit(0x4B7A, 3, 16, "right to left") -> 3
function luap.read_digit(number, digit, base, direction)
if number == 0 then return 0 end -- exception
local copy = number
local digits_total = 0
while copy >= 1 do
copy = floor(copy/base)
digits_total = digits_total + 1
end
if digit > digits_total then return false end
local exponent
if direction == "left to right" then
exponent = digits_total - digit
elseif direction == "right to left" then
exponent = digit - 1
end
local result = floor(number/base^(exponent))%base
return result
end
-- Verify whether a point is inside a rectangle
function luap.inside_rectangle(xpoint, ypoint, x1, y1, x2, y2)
-- From top-left to bottom-right
if x2 < x1 then
x1, x2 = x2, x1
end
if y2 < y1 then
y1, y2 = y2, y1
end
if xpoint >= x1 and xpoint <= x2 and ypoint >= y1 and ypoint <= y2 then
return true
else
return false
end
end
-- Convert unsigned to signed (based in <bits> bits)
function luap.signed16(num)
local maxval = 32768
if num < maxval then return num else return num - 2*maxval end
end
-- Convert unsigned byte to signed in hex string
function luap.signed8hex(num, signal)
local maxval = 128
if signal == nil then signal = true end
if num < maxval then -- positive
return fmt("%s%02X", signal and "+" or "", num)
else -- negative
return fmt("%s%02X", signal and "-" or "", 2*maxval - num)
end
end
-- Convert unsigned word to signed in hex string
function luap.signed16hex(num, signal)
local maxval = 32768
if signal == nil then signal = true end
if num < maxval then -- positive
return fmt("%s%04X", signal and "+" or "", num)
else -- negative
return fmt("%s%04X", signal and "-" or "", 2*maxval - num)
end
end
-- Transform the binary representation of base into a string
-- For instance, if each bit of a number represents a char of base, then this function verifies what chars are on
function luap.decode_bits(data, base)
local i = 1
local size = base:len()
local direct_concatenation = size <= 45 -- Performance: I found out that the .. operator is faster for 45 operations or less
local result
if direct_concatenation then
result = ""
for ch in base:gmatch(".") do
if bit.test(data, size - i) then
result = result .. ch
else
result = result .. " "
end
i = i + 1
end
else
result = {}
for ch in base:gmatch(".") do
if bit.test(data, size-i) then
result[i] = ch
else
result[i] = " "
end
i = i + 1
end
result = table.concat(result)
end
return result
end
if math.type then
function luap.is_integer(num)
return math.type(num) == "integer"
end
else
function luap.is_integer(num)
return num%1 == 0
end
end
--&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
--&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
-- JSON
-- This library is from: Jeffrey Friedl
-- Modified from original, according to the license below:
-- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i, new_val
key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--