-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlua_state.cr
More file actions
1566 lines (1377 loc) · 45.7 KB
/
lua_state.cr
File metadata and controls
1566 lines (1377 loc) · 45.7 KB
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
module Luajit
struct LuaState
alias Function = LuaState -> Int32
enum ThreadStatus
Main
Coroutine
end
# :nodoc:
MT_NAME = "luajit_cr::__LuaState__"
# :nodoc:
#
# Returns the pointer address of *state*
def self.pointer_address(state : LuaState) : String
state.to_unsafe.address.to_s
end
# :nodoc:
#
# Sets the *state* pointer address inside it's own registry
#
# Used with `#get_registry_address` for tracking whether a LuaState
# instance or thread is part of a parent LuaState instance
#
# Raises `LuaError`
def self.set_registry_address(state : LuaState) : Nil
state.push(pointer_address(state))
state.set_registry(MT_NAME)
end
# Creates a new `LuaState` and attaches a default `#at_panic` handler
def self.create : LuaState
state = new(LibLuaJIT.luaL_newstate)
set_at_panic_handler(state)
set_registry_address(state)
state
end
# Destroys *state* and gives tracked values back to Crystal
def self.destroy(state : LuaState) : Nil
begin
Trackable.remove(pointer_address(state))
ensure
state.close
end
end
getter to_unsafe : Pointer(LibLuaJIT::State)
def initialize(@to_unsafe)
end
# :nodoc:
#
# Returns the LuaState pointer address inside the registry
#
# Works across the main thread and child threads
#
# Raises `LuaError`
def get_registry_address : String
get_registry(MT_NAME)
to_string(-1).tap do
pop(1)
end
end
# Returns the version number of this core
def version : Float64
LibLuaJIT.lua_version(self).value
end
# Opens standard Lua library *type*
def open_library(type : LuaLibrary) : Nil
{% begin %}
case type
{% for t in LuaLibrary.constants.map(&.underscore) %}
{% if t == "all" %}
in .all?
LibLuaJIT.luaL_openlibs(self)
{% else %}
in .{{t.id}}?
LibLuaJIT.luaopen_{{t.id}}(self)
{% end %}
{% end %}
end
{% end %}
end
# Returns `true` if value at the given *index* has type boolean
def is_bool?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TBOOLEAN
end
# Returns `true` if value at the given *index* is a number or a string convertible to a number
def is_number?(index : Int32) : Bool
LibLuaJIT.lua_isnumber(self, index) == true.to_unsafe
end
# Returns `true` if value at the given *index* is a string or a number (which is always convertible to a string)
def is_string?(index : Int32) : Bool
LibLuaJIT.lua_isstring(self, index) == true.to_unsafe
end
# Returns `true` if value at the given *index* is a function (either C or Lua)
def is_function?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TFUNCTION
end
# Returns `true` if value at the given *index* is a C function
def is_c_function?(index : Int32) : Bool
LibLuaJIT.lua_iscfunction(self, index) == true.to_unsafe
end
# Returns `true` if value at the given *index* is a userdata (either full or light)
def is_userdata?(index : Int32) : Bool
LibLuaJIT.lua_isuserdata(self, index) == true.to_unsafe
end
# Returns `true` if value at the given *index* is a light userdata
def is_light_userdata?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TLIGHTUSERDATA
end
# Returns `true` if value at the given *index* is a thread
def is_thread?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TTHREAD
end
# Returns `true` if value at the given *index* is a table
def is_table?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TTABLE
end
# Returns `true` if value at the given *index* is nil
def is_nil?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TNIL
end
# Returns `true` if value at the given *index* is not valid (refers to an element outside the current stack)
def is_none?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) == LibLuaJIT::LUA_TNONE
end
# Returns `true` if value at the given *index* is not valid (refers to an element outside the current stack) or is nil
def is_none_or_nil?(index : Int32) : Bool
LibLuaJIT.lua_type(self, index) <= 0
end
# Returns the type of the value at the given *index*
def get_type(index : Int32) : LuaType
LuaType.new(LibLuaJIT.lua_type(self, index))
end
# Returns the name of the *lua_type* value
def type_name(lua_type : LuaType) : String
String.new(LibLuaJIT.lua_typename(self, lua_type.value) || Bytes[])
end
# Returns the name of the type of the value at the given *index*
def type_name_at(index : Int32) : String
String.new(LibLuaJIT.lua_typename(self, LibLuaJIT.lua_type(self, index)) || Bytes[])
end
# Returns `true` if the two values in indices *index1* and *index2* are equal
#
# Follows the semantics of the Lua `==` operator (i.e. may call metamethods)
#
# Raises `LuaError` if operation fails
def eq(index1 : Int32, index2 : Int32) : Bool
index1 = abs_index(index1)
index2 = abs_index(index2)
push_value(index1)
push_value(index2)
push_fn__eq
insert(-3)
pcall(2, 1) do |status|
raise LuaError.pcall_handler(self, status, "lua_equal")
end
to_boolean(-1).tap do
pop(1)
end
end
# Returns `true` if the two values in indices *index1* and *index2* are primitively equal
#
# Does not call metamethods
def raw_eq(index1 : Int32, index2 : Int32) : Bool
LibLuaJIT.lua_rawequal(self, index1, index2) == true.to_unsafe
end
# Returns `true` if the value at *index1* is smaller than the value at *index2*
#
# Follows the semantics of the Lua `<` operator (i.e. may call metamethods)
#
# Raises `LuaError` if operation fails
def less_than(index1 : Int32, index2 : Int32) : Bool
index1 = abs_index(index1)
index2 = abs_index(index2)
push_value(index1)
push_value(index2)
push_fn__less_than
insert(-3)
pcall(2, 1) do |status|
raise LuaError.pcall_handler(self, status, "lua_lessthan")
end
to_boolean(-1).tap do
pop(1)
end
end
# Converts the Lua value at *index* to `Float64`
#
# The value must be a number or a string convertible to a number, otherwise returns 0
def to_f64(index : Int32) : Float64
LibLuaJIT.lua_tonumber(self, index)
end
# :ditto:
def to_f(index : Int32) : Float64
to_f64(index)
end
# Same as `#to_f64` but returns a `Float32`
def to_f32(index : Int32) : Float32
to_f64(index).to_f32
end
# Converts the Lua value at *index* to `Int64`
#
# The value must be a number or a string convertible to a number, otherwise returns 0
#
# If the number is not an integer, it is truncated in some non-specific way
def to_i64(index : Int32) : Int64
LibLuaJIT.lua_tointeger(self, index)
end
# Same as `#to_i64` but returns a `Int32`
def to_i32(index : Int32) : Int32
to_i64(index).to_i
end
# :ditto:
def to_i(index : Int32) : Int32
to_i32(index)
end
# Converts the Lua value at *index* to `Bool`
#
# Returns `true` for any Lua value different than `false` or `nil`
#
# Returns `false` when called with a non-valid index
def to_boolean(index : Int32) : Bool
LibLuaJIT.lua_toboolean(self, index) == true.to_unsafe
end
# Converts the Lua value at *index* to a C string
#
# The Lua value must be a string or a number, otherwise returns "".
#
# If the value is a number, it also _changes the actual value in the stack
# to a string_.
def to_string(index : Int32, size : UInt64) : String
String.new(LibLuaJIT.lua_tolstring(self, index, pointerof(size)) || Bytes[])
end
# :ditto:
def to_string(index : Int32) : String
String.new(LibLuaJIT.lua_tolstring(self, index, nil) || Bytes[])
end
# Returns the "length" of the value at *index*
#
# For strings, this is the string length.
# For tables, this is the result of the length operator ('#').
# For userdata, this is the size of the block of memory allocated
# for the userdata.
# For other values, it is 0.
def size_at(index : Int32) : UInt64
LibLuaJIT.lua_objlen(self, index)
end
# Converts a value at *index* to a C function, otherwise returns `nil`
def to_c_function?(index : Int32) : LuaCFunction?
proc = LibLuaJIT.lua_tocfunction(self, index)
if proc.pointer
proc
end
end
# Same as `#to_c_function?`, but assumes value is not `nil`
def to_c_function!(index : Int32) : LuaCFunction
to_c_function?(index).not_nil!
end
# If the value at *index* is a full userdata, returns its block address
#
# If the value is a light userdata, returns its pointer
#
# Otherwise returns `nil`
def to_userdata?(index : Int32) : Pointer(Void)?
if ptr = LibLuaJIT.lua_touserdata(self, index)
ptr
end
end
# Same as `#to_userdata?`, but assumes value is not `nil`
def to_userdata!(index : Int32) : Pointer(Void)
to_userdata?(index).not_nil!
end
# Converts the value at *index* to a Lua thread, otherwise returns `nil`
def to_thread?(index : Int32) : LuaState?
if ptr = LibLuaJIT.lua_tothread(self, index)
LuaState.new(ptr)
end
end
# Same as `#to_thread?`, but assumes value is not `nil`
def to_thread!(index : Int32) : LuaState
to_thread?(index).not_nil!
end
# Converts the value at *index* to a `Pointer`
#
# The value can be a userdata, a table, a thread, or a function; otherwise, returns `nil`.
#
# Different objects will give different pointers.
# There is no way to convert the pointer back to its original value.
def to_pointer?(index : Int32) : Pointer(Void)?
if ptr = LibLuaJIT.lua_topointer(self, index)
ptr
end
end
# Same as `#to_pointer?`, but assumes value is not `nil`
def to_pointer!(index : Int32) : Pointer(Void)
to_pointer?(index).not_nil!
end
# Returns the index of the top element in the stack
#
# Because indices start at 1, this result is equal to the number of
# elements in the stack (and so 0 means an empty stack).
def size : Int32
LibLuaJIT.lua_gettop(self)
end
# Accepts any acceptable *index*, or 0, and sets the stack top
# to this index
#
# If the new top is larger than the old one, then the new
# elements are filled with `nil`.
#
# If index is 0, then all stack elements are removed.
def set_top(index : Int32) : Nil
LibLuaJIT.lua_settop(self, index)
end
# Pops *n* elements from the stack
def pop(n : Int32) : Nil
set_top(-(n) - 1)
end
# Pushes a copy of the element at *index* onto the stack
def push_value(index : Int32) : Nil
LibLuaJIT.lua_pushvalue(self, index)
end
# Removes the element at *index*, shifting down elements above to fill gap
#
# WARNING: Cannot be called with a pseudo-index, because a pseudo-index
# is not an actual stack position.
def remove(index : Int32) : Nil
LibLuaJIT.lua_remove(self, index)
end
# Moves the top element into *index*, shifting elements above to open space
#
# WARNING: Cannot be called with a pseudo-index, because a pseudo-index
# is not an actual stack position.
def insert(index : Int32) : Nil
LibLuaJIT.lua_insert(self, index)
end
# Moves the top element into the given position (and pops it),
# without shifting any element (therefore replacing the value
# at the given position)
def replace(index : Int32) : Nil
LibLuaJIT.lua_replace(self, index)
end
# Exchange values between different threads of the same global state
#
# https://www.lua.org/manual/5.1/manual.html#lua_xmove
def xmove(from : LuaState, to : LuaState, n : Int32) : Nil
LibLuaJIT.lua_xmove(from, to, n)
end
# Yields a coroutine
#
# https://www.lua.org/manual/5.1/manual.html#lua_yield
def co_yield(nresults : Int32) : Int32
LibLuaJIT.lua_yield(self, nresults)
end
# Starts and resumes a coroutine in a given thread
#
# https://www.lua.org/manual/5.1/manual.html#lua_resume
def co_resume(narg : Int32) : Int32
LibLuaJIT.lua_resume(self, narg)
end
# Returns the status of `self`
def status : LuaStatus
LuaStatus.new(LibLuaJIT.lua_status(self))
end
# Get information about the interpreter runtime stack
#
# https://www.lua.org/manual/5.1/manual.html#lua_getstack
def get_stack(level : Int32) : LuaDebug?
if LibLuaJIT.lua_getstack(self, level, out ar) == true.to_unsafe
ar
end
end
# Returns information about a specific function or function invocation
#
# https://www.lua.org/manual/5.1/manual.html#lua_getinfo
def get_info(what : String, ar : LuaDebug) : LuaDebug?
if LibLuaJIT.lua_getinfo(self, what, pointerof(ar)) != 0
ar
end
end
# Gets information about a local variable of *ar*
#
# https://www.lua.org/manual/5.1/manual.html#lua_getlocal
def get_local(ar : LuaDebug, n : Int32 = 1) : String?
if ptr = LibLuaJIT.lua_getlocal(self, pointerof(ar), n)
String.new(ptr)
end
end
# Sets the value of a local variable of *ar*
#
# https://www.lua.org/manual/5.1/manual.html#lua_setlocal
def set_local(ar : LuaDebug, n : Int32 = 1) : String?
if ptr = LibLuaJIT.lua_setlocal(self, pointerof(ar), n)
String.new(ptr)
end
end
# Gets information about a closure's upvalue
#
# https://www.lua.org/manual/5.1/manual.html#lua_getupvalue
def get_upvalue(fn_index : Int32, n : Int32) : String?
if ptr = LibLuaJIT.lua_getupvalue(self, fn_index, n)
String.new(ptr)
end
end
# Produces upvalue indices
def upvalue(index : Int32) : Int32
LibLuaJIT::LUA_GLOBALSINDEX - index
end
# Sets the value of a closure's upvalue
#
# https://www.lua.org/manual/5.1/manual.html#lua_setupvalue
def set_upvalue(fn_index : Int32, n : Int32) : String?
if ptr = LibLuaJIT.lua_setupvalue(self, fn_index, n)
String.new(ptr)
end
end
# Sets the debugging hook function
#
# https://www.lua.org/manual/5.1/manual.html#lua_sethook
def set_hook(f : LuaHook, mask : Int32, count : Int32) : Nil
LibLuaJIT.lua_sethook(self, f, mask, count)
end
# Returns the current hook function
def get_hook : LuaHook
LibLuaJIT.lua_gethook(self)
end
# Returns the current hook mask
def get_hook_mask : Int32
LibLuaJIT.lua_gethookmask(self)
end
# Returns the current hook count
def get_hook_count : Int32
LibLuaJIT.lua_gethookcount(self)
end
# :nodoc:
#
# TODO: debugging
def print_stack(uniq_value : String? = nil) : Nil
puts "####{uniq_value || ""}"
total = size
if total == 0
puts "# [0]"
else
count = -1
total.downto(1) do |index|
puts "# (#{count}) [#{index}]: #{get_type(index)}"
count -= 1
end
end
puts "###"
puts
end
# Returns `LuaGC` wrapper
def gc : LuaGC
LuaGC.new(self)
end
# Pushes onto the stack the value t[k], where t is the value at *index*,
# and k is the value at the top of the stack
#
# Pops the key from the stack (putting the resulting value in its place).
#
# As in Lua, this function may trigger a metamethod for the "index" event
#
# Raises `LuaError` if operation fails
def get_table(index : Int32) : Nil
push_value(index)
insert(-2)
push_fn__get_table
insert(-3)
pcall(2, 1) do |status|
raise LuaError.pcall_handler(self, status, "lua_gettable")
end
end
# Pushes onto the stack the value t[k], where t is the value at *index*,
# and k is the *name* of the field
#
# As in Lua, this function may trigger a metamethod for the "index" event.
#
# Raises `LuaError` if operation fails
def get_field(index : Int32, name : String) : Nil
return get_global(name) if index == LibLuaJIT::LUA_GLOBALSINDEX
return get_registry(name) if index == LibLuaJIT::LUA_REGISTRYINDEX
return get_environment(name) if index == LibLuaJIT::LUA_ENVIRONINDEX
push_value(index)
push_fn__get_field
insert(-2)
push(name)
pcall(2, 1) do |status|
raise LuaError.pcall_handler(self, status, "lua_getfield")
end
end
# Pushes onto the stack the value of the global *name*
#
# Raises `LuaError` if operation fails
def get_global(name : String) : Nil
push_fn__get_global
push(name)
pcall(1, 1) do |status|
raise LuaError.default_handler(self, status)
end
end
# Pushes onto the stack the value of the registry *name*
#
# Raises `LuaError` if operation fails
def get_registry(name : String) : Nil
push_fn__get_registry
push(name)
pcall(1, 1) do |status|
raise LuaError.default_handler(self, status)
end
end
# Pushes onto the stack the metatable associated with *tname*
# in the registry
#
# Raises `LuaError` if operation fails
#
# See `#new_metatable`
def get_metatable(tname : String) : Nil
begin
get_registry(tname)
rescue err : LuaError
raise LuaError.new("Failed to get metatable", err)
end
end
# Pushes onto the stack the value of the environment *name*
#
# Raises `LuaError` if operation fails
def get_environment(name : String) : Nil
push_fn__get_environment
push(name)
pcall(1, 1) do |status|
raise LuaError.default_handler(self, status)
end
end
# Similar to `#get_table`, but does a raw access (i.e., without metamethods)
def raw_get(index : Int32) : Nil
LibLuaJIT.lua_rawget(self, index)
end
# Pushes onto the stack the value t[n], where t is the value at *index*,
# and *n* is an array-like index
#
# The access is raw; that is, it does not invoke metamethods.
def raw_get_index(index : Int32, n : Int32) : Nil
LibLuaJIT.lua_rawgeti(self, index, n)
end
# Creates a new empty table and pushes it onto the stack
#
# *narr* represents pre-allocated array elements
#
# *nrec* represents pre-allocated non-array elements
#
# Pre-allocation is useful when you know exactly how many elements
# the table will have.
def create_table(narr : Int32, nrec : Int32) : Nil
LibLuaJIT.lua_createtable(self, narr, nrec)
end
# Creates a new empty table and pushes it onto the stack
def new_table : Nil
create_table(0, 0)
end
# Allocates a new block of memory with the given *size*,
# pushes onto the stack a new full userdata with the block address,
# and returns this address.
#
# Userdata represent C values in Lua.
# A full userdata represents a block of memory.
# It is an object (like a table): you must create it,
# it can have its own metatable, and you can detect when
# it is being collected.
# A full userdata is only equal to itself (under raw equality).
#
# When Lua collects a full userdata with a gc metamethod, Lua calls the
# metamethod and marks the userdata as finalized. When this userdata
# is collected again then Lua frees its corresponding memory.
def new_userdata(size : UInt64) : Pointer(Void)
LibLuaJIT.lua_newuserdata(self, size)
end
# :ditto:
def new_userdata(size : Int32) : Pointer(Void)
new_userdata(size.to_u64)
end
# Creates a full userdata with a type *tname*, and returns
# a pointer with the address of *ptr*
#
# See `#get_userdata`
def create_userdata(ptr : Pointer(Void), tname : String) : Pointer(UInt64)
new_userdata(sizeof(UInt64)).as(Pointer(UInt64)).tap do |ud_ptr|
ud_ptr.value = ptr.address
attach_metatable(-1, tname)
end
end
# Pushes onto the stack the metatable of the value at *index*
#
# If *index* is not valid, or value does not have a metatable,
# returns `false`.
def get_metatable(index : Int32) : Bool
LibLuaJIT.lua_getmetatable(self, index) != 0
end
# Pushes onto the stack the environment table of the value at *index*
def get_fenv(index : Int32) : Nil
LibLuaJIT.lua_getfenv(self, index)
end
# Calls a function in protected mode
#
# https://www.lua.org/manual/5.1/manual.html#lua_pcall
def pcall(nargs : Int32, nresults : Int32, errfunc : Int32 = 0) : LuaStatus
pcall(nargs, nresults, errfunc) { }
end
# Same as `#pcall`, but yields `LuaStatus` on failure
def pcall(nargs : Int32, nresults : Int32, errfunc : Int32 = 0, & : LuaStatus ->) : LuaStatus
LuaStatus.new(LibLuaJIT.lua_pcall(self, nargs, nresults, errfunc)).tap do |status|
unless status.ok?
yield status
end
end
end
# Calls the C function *block* in protected mode
#
# All values returned by *block* are discarded.
#
# NOTE: Adopted from Lua 5.3, because LuaJIT's version has some
# inconsistencies when dealing with error handling that made it
# hard to work with.
def c_pcall(&block : Function) : LuaStatus
push(block)
pcall(0, 0)
end
# Loads and runs the given *str*
def execute(str : String) : LuaStatus
status = LuaStatus.new(LibLuaJIT.luaL_loadstring(self, str))
return pcall(0, LibLuaJIT::LUA_MULTRET) if status.ok?
status
end
# Loads and runs the given *str*
#
# Raises `LuaError` if operation fails
def execute!(str : String) : Nil
status = execute(str)
raise LuaError.default_handler(self, status) unless status.ok?
end
# Loads and runs the given *path*
def execute(path : Path) : LuaStatus
status = LuaStatus.new(LibLuaJIT.luaL_loadfile(self, path.to_s))
return pcall(0, LibLuaJIT::LUA_MULTRET) if status.ok?
status
end
# Loads and runs the given *path*
#
# Raises `LuaError` if operation fails
def execute!(path : Path) : Nil
status = execute(path)
raise LuaError.default_handler(self, status) unless status.ok?
end
# Dumps a Lua function as a binary chunk at *index*
#
# Raises `LuaError` if operation fails
def dump_chunk(index : Int32 = -1) : IO::Memory
io = IO::Memory.new
proc = LibLuaJIT::Writer.new do |_L, _p, _sz, _ud|
_io = Box(typeof(io)).unbox(_ud)
slice = _p.as(Pointer(UInt8)).to_slice(_sz)
_io.write(slice)
0
end
push_value(index)
status = LibLuaJIT.lua_dump(self, proc, Box(typeof(io)).box(io))
pop(1)
unless status == 0
raise LuaError.new("Failed to dump lua function")
end
io.rewind
end
# Loads *io* as a Lua chunk
#
# *name* is the chunk name, used for debug information and error messages.
#
# See `#dump_chunk`
def load_chunk(io : IO::Memory, name : String) : LuaStatus
LuaStatus.new(LibLuaJIT.luaL_loadbuffer(self, io.buffer, io.size, name))
end
# Pops a key from the stack, and pushes a key-value pair from the
# table at *index* (the "next" pair after the given key).
#
# If there are no more elements in the table, then returns `false` (and pushes nothing).
#
# While traversing a table, do not call `#to_string` directly on a key,
# unless you know that the key is actually a string. Recall that
# `#to_string` changes the value at the given index; this confuses
# the next call to `#next`.
#
# Raises `LuaError` if operation fails
#
# A typical traversal looks like this:
# ```
# # table is in the stack at index 't'
# state.push(nil)
# while state.next(t)
# # uses 'key' (at index -2) and 'value' (at index -1)
# puts "#{state.type_name_at(-2)} - #{state.type_name_at(-1)}"
# # removes 'value'; keeps 'key' for next iteration
# state.pop(1)
# end
# ```
def next(index : Int32) : Bool
push_value(index)
insert(-2)
push_fn__next
insert(-3)
pcall(2, 3) do |status|
raise LuaError.pcall_handler(self, status, "lua_next")
end
to_boolean(-1).tap do |result|
pop(1)
pop(2) unless result
end
end
# Concatenates the *n* values at the top of the stack, pops them,
# and leaves the result at the top
#
# If *n* == 1, does nothing
#
# If *n* == 0, pushes empty string
#
# Raises `LuaError` if operation fails
def concat(n : Int32) : Nil
push("") if n < 1
return if n < 2
push_fn__concat
insert(-(n) - 1)
pcall(n, 1) do |status|
raise LuaError.pcall_handler(self, status, "lua_concat")
end
end
# Pushes a `nil` value onto the stack
def push(_x : Nil) : Nil
LibLuaJIT.lua_pushnil(self)
end
# Pushes a `Float64` onto the stack
def push(x : Float64) : Nil
LibLuaJIT.lua_pushnumber(self, x)
end
# Pushes a `Float32` converted to a `Float64` onto the stack
def push(x : Float32) : Nil
push(x.to_f64)
end
# Pushes an `Int64` onto the stack
def push(x : Int64) : Nil
LibLuaJIT.lua_pushinteger(self, x)
end
# Pushes an `Int32` converted to an `Int64` onto the stack
def push(x : Int32) : Nil
push(x.to_i64)
end
# Pushes a `String` onto the stack
def push(x : String) : Nil
LibLuaJIT.lua_pushstring(self, x)
end
# Pushes a `Char` converted to a `String` onto the stack
def push(x : Char) : Nil
push(x.to_s)
end
# Pushes a `Symbol` converted to a `String` onto the stack
def push(x : Symbol) : Nil
push(x.to_s)
end
# Pushes a C function onto the stack
def push(x : LuaCFunction) : Nil
LibLuaJIT.lua_pushcclosure(self, x, 0)
end
# Pushes a C closure onto the stack
def push(x : Function) : Nil
push_fn_closure do |state|
x.call(state)
end
end
# Pushes a boolean onto the stack
def push(x : Bool) : Nil
LibLuaJIT.lua_pushboolean(self, x)
end
# Pushes a light userdata onto the stack
#
# A light userdata is equivalent to a `Pointer`
def push(x : Pointer(Void)) : Nil
LibLuaJIT.lua_pushlightuserdata(self, x)
end
def push(x : Array) : Nil
create_table(x.size, 0)
x.each_with_index do |item, index|
push(index + 1)
push(item)
set_table(-3)
end
end
def push(x : Hash) : Nil
create_table(0, x.size)
x.each do |key, value|
push(key)
push(value)
set_table(-3)
end
end
# Pushes a C function onto the stack
def push_fn(&block : LuaCFunction) : Nil
push(block)
end
# Pushes a C closure onto the stack
def push_fn_closure(&block : Function) : Nil
box = Box(typeof(block)).box(block)
track(box)
proc = LuaCFunction.new do |l|
state = LuaState.new(l)
begin
Box(typeof(block)).unbox(state.to_userdata!(state.upvalue(1))).call(state)
rescue err
LibLuaJIT.luaL_error(state, err.inspect)
end
end
push(box)
LibLuaJIT.lua_pushcclosure(self, proc, 1)
end
# Pushes `self` onto its own stack and returns its thread status
#
# `ThreadStatus::Main` is returned when `self` represents the main
# thread, otherwise `ThreadStatus::Coroutine` is returned.
def push_thread : ThreadStatus
if LibLuaJIT.lua_pushthread(self) == 1
ThreadStatus::Main
else
ThreadStatus::Coroutine
end
end
# Does the equivalent to t[k] = v, where t is the value at *index*,
# v is the value at top of stack, and k the value just behind v
#
# Pops both key and value from the stack.
#
# Raises `LuaError` if operation fails
def set_table(index : Int32) : Nil
push_value(index)
insert(-3)
push_fn__set_table
insert(-4)
pcall(3, 0) do |status|
raise LuaError.pcall_handler(self, status, "lua_settable")
end
end
# Does the equivalent to t[k] = v, where t is the value at *index*,
# *k* is the key, and v is the value at top of stack.
#
# Pops the value from the stack.
#
# Raises `LuaError` if operation fails
def set_field(index : Int32, k : String) : Nil
return set_global(k) if index == LibLuaJIT::LUA_GLOBALSINDEX
return set_registry(k) if index == LibLuaJIT::LUA_REGISTRYINDEX
return set_environment(k) if index == LibLuaJIT::LUA_ENVIRONINDEX
push_value(index)
insert(-2)
push_fn__set_field
insert(-3)
push(k)
pcall(3, 0) do |status|
raise LuaError.pcall_handler(self, status, "lua_setfield")
end
end
# Pops a value from the stack and sets it as the new value of global *name*
#
# Raises `LuaError` if operation fails
def set_global(name : String) : Nil
push_fn__set_global
insert(-2)
push(name)
pcall(2, 0) do |status|
raise LuaError.pcall_handler(self, status, "lua_setglobal")
end
end
# Pops a value from the stack and sets it as the new value of registry *name*
#
# Raises `LuaError` if operation fails
def set_registry(name : String) : Nil
push_fn__set_registry