-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlua.ml
1785 lines (1595 loc) · 48.9 KB
/
lua.ml
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
(**
Wrapper for Lua states etc
@since 2013-03-22
*)
exception LuaException of string
let escape = Netencoding.Html.encode ~in_enc:`Enc_utf8 ~unsafe_chars:Netencoding.Html.unsafe_chars_html4 ()
open Lua_api
let (|>) x g = g x
let (<|) g x = g x
(** Game state *)
type lua = {
state : Lua_api_lib.state
}
(**
Representation of how cards look in the lua state
*)
type lua_card = {
c_cardname : string; (* Like card1, card2 ... *)
c_deck_id : int;
c_card_id : int;
c_nr : int;
c_onpickup : string;
c_onplay : string;
c_title : string;
c_text : string;
c_img : string;
c_sound : string;
c_dir : string;
}
let log str =
ignore (Lwt_io.eprintl str)
(**
Wrapper module for table ds_api and ds_api_param
*)
module Api = struct
exception ApiException of string
exception Api_not_found
(**
Param = parameter, argument to api function
*)
type param = {
api_id : int;
param_name : string;
param_desc : string;
param_type : string;
(**
Api function with doc
*)
} and api = {
id : int;
name : string;
script : string;
active : bool;
version : int;
signature : string;
desc : string;
internal : bool;
params : param list;
} with value, type_of
let html_of_api_param ap =
Printf.sprintf "
<tr><td></td><td><b>• </b></td><td class=param>%s</td><td>:</td><td class=type>%s</td><td> %s</td>
"
ap.param_name
ap.param_type
ap.param_desc
let html_of_api api =
Printf.sprintf "
<span class='func_sig'>%s</span><span class=internal>%s</span><br />
<div class='func_desc'>
<p>%s</p>
%s <!-- Description -->
%s <!-- Params -->
%s <!-- Table end tag -->
<br />
</div>
"
api.signature
(if api.internal then " - Internal!" else "")
api.desc
(if List.length api.params > 0 then
"
<p style='color: rgb(92, 101, 133);'>Parameters:</p>
<table>
"
else
""
)
(Misc.implode_list (List.map (fun ap -> html_of_api_param ap) api.params))
(if List.length api.params > 0 then "</table>" else "")
let html_of_apis apis =
let html_list = List.map (fun api -> html_of_api api) apis in
Misc.implode_list html_list
let api_of_row row =
assert(Array.length row = 8);
let get fn n = match row.(n) with
| Some i -> fn i
| None -> raise Api_not_found
in
let get' = get (fun x -> x) in
try
{
id = get int_of_string 0;
name = get' 1;
script = get' 2;
active = get (fun x -> x = "1") 3;
version = get int_of_string 4;
signature = get' 5;
desc = get' 6;
internal = get (fun x -> x = "1") 7;
params = []
}
with
_ -> raise (ApiException "Could not contruct api of row")
let api_param_of_row row =
assert(Array.length row = 4);
let get fn n = match row.(n) with
| Some i -> fn i
| None -> raise Api_not_found
in
let get' = get (fun x -> x) in
try
{
api_id = get int_of_string 0;
param_name = get' 1;
param_desc = get' 2;
param_type = get' 3;
}
with
_ -> raise (ApiException "Could not contruct api param of row")
(**
Get all api functions and its docs.
@param db the db returned by open_db
@return api list
*)
let get_apis db =
let query = "
SELECT
id,
name,
script,
active,
version,
signature,
`desc`,
internal
FROM
ds_api
ORDER BY
name ASC
" in
let stmt = Db.create_stmt db query in
let result = Db.execute_stmt stmt [||] in
let apis = Db.list_of_result result api_of_row in
let query = "
SELECT
api_id,
name,
`desc`,
type
FROM
ds_api_param
" in
let stmt = Db.create_stmt db query in
let result = Db.execute_stmt stmt [||] in
let api_params = Db.list_of_result result api_param_of_row in
(* Traverse params once for each api. Better than call DB once for each api function? *)
ExtLib.List.map (fun api ->
let my_params = ExtLib.List.filter (fun param ->
param.api_id = api.id
) api_params in
{api with params = my_params}
) apis
end
module Api_datastructure = struct
exception ApiStructureException of string
exception Api_datastructure_not_found
(**
Param = parameter, argument to api function
*)
type elem = {
api_id : int;
elem_name : string;
elem_desc : string;
elem_type : string;
(**
Api function with doc
*)
} and api_datastructure = {
id : int;
name : string;
desc : string;
elems : elem list;
}
let html_of_api_elem ap =
Printf.sprintf "
<tr><td></td><td><b>• </b></td><td class=param>%s</td><td>:</td><td class=type>%s</td><td> %s</td>
"
ap.elem_name
ap.elem_type
ap.elem_desc
let html_of_api_datastructure api =
Printf.sprintf "
<span class='func_sig'>%s</span><br />
<div class='func_desc'>
<p>%s</p>
%s <!-- Table begin -->
%s <!-- Elems -->
%s <!-- Table end tag -->
<br />
</div>
"
api.name
api.desc
(if List.length api.elems > 0 then
"
<p style='color: rgb(92, 101, 133);'>Elements:</p>
<table>
"
else
""
)
(Misc.implode_list (List.map (fun ap -> html_of_api_elem ap) api.elems))
(if List.length api.elems > 0 then "</table>" else "")
let html_of_api_datastructures apis =
let html_list = List.map (fun api -> html_of_api_datastructure api) apis in
Misc.implode_list html_list
let api_of_row row =
assert(Array.length row = 3);
let get fn n = match row.(n) with
| Some i -> fn i
| None -> raise Api_datastructure_not_found
in
let get' = get (fun x -> x) in
try
{
id = get int_of_string 0;
name = get' 1;
desc = get' 2;
elems = []
}
with
_ -> raise (ApiStructureException "Could not contruct api of row")
let api_elem_of_row row =
assert(Array.length row = 4);
let get fn n = match row.(n) with
| Some i -> fn i
| None -> raise Api_datastructure_not_found
in
let get' = get (fun x -> x) in
try
{
api_id = get int_of_string 0;
elem_name = get' 1;
elem_desc = get' 2;
elem_type = get' 3;
}
with
_ -> raise (ApiStructureException "Could not contruct api param of row")
(**
Get all API data structures
@param db the db returned by open_db
@return api list
*)
let get_apis db =
let query = "
SELECT
id,
name,
`desc`
FROM
ds_api_datastructure
" in
let stmt = Db.create_stmt db query in
let result = Db.execute_stmt stmt [||] in
let apis = Db.list_of_result result api_of_row in
let query = "
SELECT
api_datastructure_id,
name,
`desc`,
type
FROM
ds_api_datastructure_elem
" in
let stmt = Db.create_stmt db query in
let result = Db.execute_stmt stmt [||] in
let api_elems = Db.list_of_result result api_elem_of_row in
(* Traverse elems once for each api. Better than call DB once for each api function? *)
ExtLib.List.map (fun api ->
let my_elems = ExtLib.List.filter (fun elem ->
elem.api_id = api.id
) api_elems in
{api with elems = my_elems}
) apis
end
(**
* Peano numbers, to statically check `assert(n > 0)` and the like
* Experimental.
*
* @since 2013-03-29
*)
module Nat : sig
type z = Z
type 'n s = S of 'n
type ('n) nat =
Zero : (z) nat
| Succ : ('n) nat -> ('n s) nat
type some_nat = Some : 'n nat -> some_nat
val inc : ( 'n) nat -> ( 'n s) nat
val dec : ('n s) nat -> 'n nat
val to_int : ( 'n) nat -> int
val d0 : z nat
val d1 : z s nat
val d2 : z s s nat
val d3 : z s s s nat
end = struct
type z = Z
type 'n s = S of 'n
type ( 'n) nat =
Zero : ( z) nat
| Succ : ( 'n) nat -> ( 'n s) nat
type some_nat = Some : 'n nat -> some_nat
let inc n = Succ n
let dec (Succ n) = n
let rec to_int : type n . n nat -> int = function
| Succ a -> 1 + (to_int a)
| Zero -> 0
let rec of_int = function
0 -> Some Zero
| n ->
let (Some nat) = of_int (n - 1) in
Some (Succ nat)
let d0 = Zero
let d1 = inc d0
let d2 = inc d1
let d3 = inc d2
end
(**
* Generates an lua error @msg on state @s
* This will halt the Lua state
*
* @param s raw state (no LUA)
* @param msg string; error message
*)
let error s msg =
Lua_api.Lua.pushstring s msg;
Lua_api.Lua.error s
(**
Linear type module for adding new table to Lua state, etc
The state of the stack will be represented by phantom types.
The order of operations will be controlled statically.
Thus it's not possible to push a number or string on the stack before pushing an index for that table.
Usage:
let s = newstate() in
let s = newtable s in
...
setglobal s "table_name"
[< `foo | `bar ]
foo ELLER bar ELLER foo och bar
"something is a subset of this"
[> `foo | `bar]
foo och bar, ELLER foo och bar och annat
måste ha både foo och bar, minst
"this is a subsut of something"
@since 2013-03-27
*)
module LUA: sig
(* Possible types on stack *)
type ('s, 't) t (* type *)
type empty = unit * unit
type empty_t = (unit, unit) t
type any_atomic = [`string | `number | `bool]
type any = [`string | `number | `bool | `table | `fn | `nil | `fn_res]
(* Basics *)
(*val newstate : unit -> empty t*)
val newstate : unit -> (unit, unit) t
val endstate : (unit, unit) t -> unit
val to_lua : (unit, unit) t -> Lua_api.Lua.state
val of_lua : Lua_api.Lua.state -> (unit, unit) t
val error : (('a, 'b) t) -> string -> unit
(* Interacting with tables *)
val pushindex : ([`table], 'a) t -> string -> ([`string], [`table] * 'a) t
(*val pushstring : ([`index], [`table] * 'a) t -> string -> ((string, 's n_table index) value) t*)
val pushstring : ('a, 'b) t -> string -> ([`string], 'a * 'b) t
(*val pushnumber : ('s n_table string) t -> float -> ((float, 's n_table string) value) t*)
val pushnumber : ('a, 'b) t -> float -> ([`number], 'a * 'b) t
val pushnumber2 : ('a, 'b) t -> float -> ([`number], 'a * 'b) t
val pushboolean : ('a, 'b) t -> bool -> ([`bool], 'a * 'b) t
(*val settable : (('a, 's n_table string) value) t -> ('s n_table) t*)
val settable : ([< any], [`string] * ([`table] * 'a)) t -> ([`table], 'a) t
val setsubtable : ([`table], [`table] * 'a) t -> ([`table], 'a) t
val istable : ([`table], 'a) t -> bool
val newtable : ('a, 'b) t -> ([`table], ('a * 'b)) t
val newsubtable : ([`table], 'a) t -> string -> ([`table], [`table] * 'a) t
val setglobal : ([< any], 'a * 'b) t -> string -> ('a, 'b) t
val setmetatable : ([`table], [`table] * 'a) t -> ([`table], 'b) t
(* getglobal pushes an "any value" on the stack, since we, at compile time, don't know what it is *)
val getglobal : ('a, 'b) t -> string -> ([< any], 'a * 'b) t
val gettable : ('a, 'b) t -> string -> ([`table], 'a * 'b) t
(* Pop first element from stack *)
val pop : ('a, 'b * 'c) t -> ('b, 'c) t
val getfield : ([`table], 'b) t -> string -> ([< any], [`table] * 'b) t
val setfield : ([< any], ([`table] * 'a)) t -> string -> ([`table], 'a) t
val setnumber : ([`table], 'a) t -> string * float -> ([`table], 'a) t
val getnumber : ([`table], 'a) t -> string -> ([`table], 'a) t * float
val getint : ([`table], 'a) t -> string -> ([`table], 'a) t * int
val tonumber : ([`number], 'a) t -> ([`number], 'a) t * float
val toint : ([`number], 'a) t -> ([`number], 'a) t * int
val setstring : ([`table], 'a) t -> string * string -> ([`table], 'a) t
val getstring : ([`table], 'a) t -> string -> ([`table], 'a) t * string
val tostring : ([`string], 'a) t -> ([`string], 'a) t * string
val setboolean : ([`table], 'a) t -> string * bool -> ([`table], 'a) t
val getboolean : ([`table], 'a) t -> string -> ([`table], 'a) t * bool
val setfunc : ([`table], 'a) t -> string * string -> ([`table], 'a) t
val runstring : empty_t -> string -> string -> empty_t
val objlen : ([`table], 'a) t -> ([`table], 'a) t * int
val ref_ : ([< any], 'a * 'b) t -> int -> ('a, 'b) t * int
(** Check type of item at top of stack *)
val checktype : ('a, 'b) t -> Lua_api_lib.lua_type -> unit
val isnil : ('a, 'b) t -> bool
val typename : ('a, 'b) t -> string
(* Iterate array table *)
(* Not done *)
val push_dummykey : ([`table], 'a) t -> ([`string], [`table] * 'a) t
val pushnil : ('a, 'b) t -> ([`nil], 'a * 'b) t
(*val next : 's*)
(*val iter_array : 'string table t -> (unit -> unit) -> 's table t *)
val pushcfunction : empty_t -> string -> Lua_api.Lua.oCamlFunction -> unit
val pushcfunction0 : empty_t -> string -> (empty_t -> int) -> unit
val pushcfunction1 : empty_t -> string -> (([< any], empty) t -> int) -> unit
val pushcfunction2 : empty_t -> string -> (([< any], [< any] * empty) t -> int) -> unit
val pushcfunction3 : empty_t -> string -> (([< any], [< any] * ([< any] * empty)) t -> int) -> unit
val pushcfunction4 : empty_t -> string -> (([< any], [< any] * ([< any] * ([< any] * empty))) t -> int) -> unit
(*val to_lua : empty t -> Lua_api_lib.state*)
val loadbuffer : empty_t -> string -> string -> empty_t
(*val pcall : empty_t -> int -> int -> int -> empty_t*)
(* Calling Lua functions *)
val getfn : empty_t -> string -> ([`fn], empty) t (* Set Lua function name to call *)
(*val setarg_number : ([`fn], 'a) t -> float -> ([`arg], [`fn] * 'a) t (* Set arg, float *)*)
(*val setarg_table : ([`fn], 'a) t -> string -> ([`arg], [`fn] * 'a) t (* Set arg, table *)*)
(*val setarg_subtable : ('s fn) t -> string -> string -> ('s arg fn) t (* Set arg, table *)*)
(* val fnargs_toint : ? TODO: Use GADT for this? Overkill? Left as excercise... *)
val pcall_fn1 : ([< any], [`fn] * 'a) t -> ([< any], 'a) t (* Call Lua function TODO: Will accept pcall_fn3 too, since 's! *)
val pcall_fn2 : ([< any], ([< any] * ([`fn] * 'a))) t -> ([< any], 'a) t
val pcall_fn2_noresult : ([< any], ([< any] * ([`fn] * empty))) t -> empty_t
val pcall_fn1_noresult : ([< any], ([`fn] * empty)) t -> empty_t
val pcall_fn0_noresult : ([`fn], 'a * 'b) t -> ('a, 'b) t
val pcall_fn3 : ([< any], ([< any] * ([< any] * ([`fn] * empty)))) t -> ([< any], empty) t
val pcall_fn3_noresult : ([< any], ([< any] * ([< any] * ([`fn] * empty)))) t -> empty_t
val pcall_fn4_noresult : ([< any], ([< any] * ([< any] * ([< any] * ([`fn] * empty))))) t -> empty_t
val fn_getnumber : ([`fn_res], empty) t -> empty_t * float (* Get result, float *)
val fn_getstring : ([`fn_res], empty) t -> empty_t * string (* Get result, string *)
val fn_getbool : ([`fn_res], empty) t -> empty_t * bool
(* Removes element at -2 from stack *)
val remove_second : ('a, 'b * ('c * 'd)) t -> ('a, 'c * 'd) t
(* Array operations *)
val rawgeti : ([`table], 'a) t -> int -> ([< any], [`table] * 'a) t
val rawgeti_registryindex : ('a, 'b) t -> int -> ([< any], 'a * 'b) t
val rawseti : ([< any], [`table] * ('a * 'b)) t -> int -> ([`table], 'a * 'b) t
val loop_rawgeti : ([`table] , 'a) t -> (([`table], 'a) t -> ([`table], 'a) t) -> unit
val fold_rawgeti : ([`table], 'a) t -> (([< any], [`table] * 'a) t -> (([< any], [`table] * 'a) t * 'b)) -> 'b list
(*val fold_with_rawgeti : *)
end = struct
type ('s, 't) t = Lua_api_lib.state
(*type (_, _) t = data * lua_state and data = Array of ... | Stack of ...*)
type empty = unit * unit
type empty_t = (unit, unit) t
type any_atomic = [`string | `number | `bool]
type any = [`string | `number | `bool | `table | `fn | `nil | `fn_res]
let to_lua s = s
let of_lua s = s
(** Get new lua state and open libs *)
let newstate () =
let state = LuaL.newstate() in
LuaL.openlibs state;
state
(**
* Consumes an empty state and return unit
*
* @param state empty t
* @return unit
*)
let endstate state =
()
let error s msg =
Lua_api.Lua.pushstring s msg;
Lua_api.Lua.error s
(** Prepare stack for new table *)
let newtable state =
Lua.newtable state;
state
(** Add a subtable to a table field *)
let newsubtable state table_name =
Lua.pushstring state table_name;
Lua.newtable state;
state
(** Index on table on stack, e.g. {string = value} *)
let pushindex state str =
Lua.pushstring state str;
state
(** Value for an index *)
let pushstring state str =
Lua.pushstring state str;
state
(** Value for an index *)
let pushnumber state n =
Lua.pushnumber state n;
state
let pushnumber2 state n =
Lua.pushnumber state n;
state
let pushboolean state b =
Lua.pushboolean state b;
state
(**
Push a function to a table index
@param state see val in sig
@param func string, like "return function() bla end"
@return state
*)
(*
let pushfunc state func =
let ts = LuaL.loadstring state func in
(match thread_state with
| Lua.LUA_OK -> ()
| err ->
let err_msg = Lua.tostring state (-1) in
Lua.pop state 1; (* Pop message from stack *)
failwith ("pushfunc: LuaL.loadstring: " ^ (match err_msg with Some s -> s | None ->
raise Not_found))
);
Lua.pcall state 0 1 0;
state
*)
(** Pops index/value pair from stack and push it to table *)
let settable state =
ignore (Lua.settable state (-3));
state
(** Set subtable on table *)
let setsubtable state =
ignore(Lua.settable state (-3));
state
(** Pops table from stack and push it to lua state *)
let setglobal state table_name =
Lua.setglobal state table_name;
state
(** Assumes stack -1 => metatable, -2 => table
Pops metatable from stack, and set it as metatable for table at index -2 *)
let setmetatable s =
ignore(Lua.setmetatable s (-2)); (* 5.1 return int, 5.2 return void *)
s
(** Get existing table from state and push it to stack *)
let getglobal state table_name =
Lua.getglobal state table_name;
state
let gettable s str =
Lua.getglobal s str;
s
(*
if Lua.istable s (-1) then
s
else
raise error ("Not a table: " ^ str))
*)
(** Pop 1 element from stack *)
let pop state =
Lua.pop state 1;
state
(** Pop subtable table from stack *)
let popsubtable state =
Lua.pop state 1;
state
(**
Assuming table is on top of stack
Set string
*)
let setstring s (index, value) =
let s = pushindex s index in
let s = pushstring s value in
settable s
(**
* Table on stack
* Set boolean value
*)
let setboolean s (index, value) =
let s = pushstring s index in
let s = pushboolean s value in
settable s
(**
Assuming table is on top of stack
Push field to table in lua state
@param s lua state from LUA module
@param index string
@param value float
@return unit
*)
let setnumber s (index, value) =
let s = pushindex s index in
let s = pushnumber s value in
settable s
(** Internal function. Handle thread state after pcall or loadstring *)
let check_thread ts state = match ts with
| Lua.LUA_OK -> ()
| err ->
let err_msg = Lua.tostring state (-1) in
Lua.pop state 1; (* Pop message from stack *)
failwith ("pushfunc: LuaL.loadstring: " ^ (match err_msg with Some s -> s | None -> raise Not_found))
(**
Push function in table to Lua, like player1 = {onpickup = function () do_something end }
*)
let setfunc s (index, func_string) =
let s = pushstring s index in
check_thread (LuaL.loadstring s ("return " ^ (match func_string with "" -> " function () end" | s -> s))) s;
check_thread (Lua.pcall s 0 1 0) s;
ignore(Lua.settable s (-3)); (* TODO: Why this return int in OCaml version? *)
s
(**
Push field from table on top of stack
*)
let getfield s key =
Lua.getfield s (-1) key;
s
(** Assumes stack: -1 => value, -2 => table
t[k] = v
Pops value, leaving stack: -1 => table *)
let setfield s key =
Lua.setfield s (-2) key;
s
(**
Return float value from table.
@param state lua state
@param key string, key in table
@return (state, float)
*)
let getnumber state key =
Lua.getfield state (-1) key;
if not (Lua.isnumber state (-1)) then
error state ("Not number in table field " ^ key);
let n = Lua.tonumber state (-1) in
Lua.pop state 1;
(state, n)
(** As above, but returns int *)
let getint state key =
Lua.getfield state (-1) key;
if not (Lua.isnumber state (-1)) then
error state ("Not number in table field " ^ key);
let n = Lua.tonumber state (-1) in
Lua.pop state 1;
(state, int_of_float n)
(* Return number on top of stack, NO POP *)
let tonumber s =
if not (Lua.isnumber s (-1)) then
error s "tonumber: no number";
let nr = Lua.tonumber s (-1) in
(s, nr)
(* Return number to int on top of stack, NO POP *)
let toint s =
if not (Lua.isnumber s (-1)) then
error s "tonumber: no number";
let nr = Lua.tonumber s (-1) in
(s, int_of_float nr)
let istable state =
Lua.istable state (-1)
(**
Return string field from table.
@param state lua state
@param key string, key in table
@return string
*)
let getstring state key =
Lua.getfield state (-1) key;
if not (Lua.isstring state (-1)) then
error state ("Not string in table field " ^ key);
match Lua.tostring state (-1) with
| Some s ->
Lua.pop state 1;
(state, escape s)
| None ->
Lua.pop state 1;
error state ("Found no string in table field " ^ key)
(** Return string, if top of stack is string, AND DOES NOT POP *)
let tostring state =
if not (Lua.isstring state (-1)) then
failwith ("Not string at top of stack");
match Lua.tostring state (-1) with
| Some s ->
(state, escape s)
| None ->
failwith ("Found no string at top of stack")
(**
* Return boolean field from table on stack
*)
let getboolean state key =
Lua.getfield state (-1) key;
if not (Lua.isboolean state (-1)) then
failwith ("Not bool in table field " ^ key);
let n = Lua.toboolean state (-1) in
Lua.pop state 1;
(state, n)
(** Push an OCaml function into state, so it can be executed by the lua script *)
let pushcfunction state name func =
Lua.pushcfunction state func;
Lua.setglobal state name
(** Push a function which takes zero arg in Lua *)
let pushcfunction0 state name func =
Lua.pushcfunction state func;
Lua.setglobal state name
(** Push a function which takes one arg in Lua *)
let pushcfunction1 state name func =
Lua.pushcfunction state func;
Lua.setglobal state name
(** Push a function which takes two args in Lua *)
let pushcfunction2 state name func =
Lua.pushcfunction state func;
Lua.setglobal state name
(** Push a function which takes three args in Lua *)
let pushcfunction3 state name func =
Lua.pushcfunction state func;
Lua.setglobal state name
(** Push a function which takes three args in Lua *)
let pushcfunction4 state name func =
Lua.pushcfunction state func;
Lua.setglobal state name
(**
Execute a lua string
@param state
@param str string; string to execute
@param chunkname string; name of chunk (will appear in error message)
@return state
@raise fail if thread state not ok
*)
let runstring state str chunkname =
(* Push the traceback function on the stack *)
let traceback s =
Lua.getfield s Lua_api_lib.globalsindex "debug";
Lua.getfield s (-1) "traceback";
Lua.pushvalue s 1;
Lua.pushinteger s 2;
Lua.call s 2 1;
(*
(match ts with
| Lua.LUA_OK ->
()
| err ->
begin
log "traceback: could not run debug.traceback";
end
);
*)
let trace = (match Lua.tostring s (-1) with
| Some s -> s
| None -> "No trace"
) in
(* Replace \n with <br />, etc *)
let regexp = Str.regexp "\\\n" in
let trace = Str.global_replace regexp "<br />" trace in
let regexp = Str.regexp "\\\t" in
let trace = Str.global_replace regexp " " trace in
let trace = "<pre>" ^ trace ^ "</pre>" in
Lua.pop state 1;
Lua.pushstring state trace;
1
in
Lua.pushcfunction state traceback;
let ts = LuaL.loadbuffer state str chunkname in
(match ts with
| Lua.LUA_OK ->
()
| err ->
begin
let err_msg = Lua.tostring state (-1) in
Lua.pop state 1;
raise (LuaException ("runstring: Could not loadbuffer script " ^ chunkname ^ ": " ^ (match err_msg with Some s -> s | None ->
raise Not_found)))
end
);
(*let thread_state = Lua.pcall state 0 0 ((Lua.gettop state) - 1) in*)
let thread_state = Lua.pcall state 0 0 (-2) in
match thread_state with
| Lua.LUA_OK ->
state
| err ->
begin
let err_msg = match Lua.tostring state (-1) with
| Some s -> s
| None ->
raise (LuaException "runstring: Could no find err_mgs")
in
Lua.pop state 1;
raise (LuaException ("runstring: Could not pcall lua script " ^ chunkname ^ ": " ^ err_msg))
end
(**
Length of table
*)
let objlen s =
let i = Lua.objlen s (-1) in
(s, i)
(** Get a unique int ref, preferebly used with the registry index *)
let ref_ s i =
let j = Lua_api.LuaL.ref_ s i in
(s, j)
(** Check type of item at top of stack *)
let checktype s t =
LuaL.checktype s (-1) t
let isnil s =
Lua.isnil s (-1)
let typename s =
LuaL.typename s (-1)
(**
Push a dummy key before using next first time
@param s Lua state
*)
let push_dummykey s =
Lua.pushnil s;
s
let pushnil s =
Lua.pushnil s;
s
(**
Push next key/value pair on stack.
Assumes key/dummykey
*)
(*
let next s =
Lua.next s (-2);
s
*)
(**
Iterates through an array-like table @l times, and run @fn for each value
Assumes the table to iterate is top of stack
@param s Lua state
@param l length; timer to iterate
@param fn unit -> unit; function run on each value
*)
(*
let iter_array s l fn =
let s = push_dummykey s' in (* stack: -1 => nil, -2 => hand, -3 => player *)
let rec iter s' n =
if n > l then
[]
else
begin
Lua_api.Lua.next s' (-2); (* stack: -1 => value/card, -2 => key/array index, -3 => hand, -4 => player *)
let field = Lua_api.Lua.getfield s' (-1) "card_id" in (* stack: -1 => card_id, -2 => value/card, -3 => key/array index, -4 => hand, -5 => player *)
if not (Lua_api.Lua.isnumber s' (-1)) then
failwith ("Not number in table field card_id");
let card_id' = Lua_api.Lua.tonumber s' (-1) in
Lua_api.Lua.pop s' 2; (* stack: -1 => key/array index, -2 => hand, -3 => player *)
card_id' :: get_card_ids (n + 1)
end
in
let _ = iter s' 1 in
Lua_api.Lua.pop s' 2
*)
(**
Loads lua script/buffer into state
@param state lua state
@param buffer string; lua code
*)
let loadbuffer state buffer chunkname =
check_thread (LuaL.loadbuffer state buffer chunkname) state;
state
(**
Run lua code in buffer
@param state lua state
@param i j k ?
@return state
@raise failwith if thread state != LUA_OK after call; raise Not_found if no error message was found
*)