-
Notifications
You must be signed in to change notification settings - Fork 191
/
lua.go
1531 lines (1382 loc) · 50.2 KB
/
lua.go
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
package lua
import (
"errors"
"fmt"
"io"
"math"
"strings"
)
// MultipleReturns is the argument for argCount or resultCount in ProtectedCall and Call.
const MultipleReturns = -1
// Debug.Event and SetDebugHook mask argument values.
const (
HookCall, MaskCall = iota, 1 << iota
HookReturn, MaskReturn
HookLine, MaskLine
HookCount, MaskCount
HookTailCall, MaskTailCall
)
// Errors introduced by the Lua VM.
var (
SyntaxError = errors.New("syntax error")
MemoryError = errors.New("memory error")
ErrorError = errors.New("error within the error handler")
FileError = errors.New("file error")
)
// A RuntimeError is an error raised internally by the Lua VM or through Error.
type RuntimeError string
func (r RuntimeError) Error() string { return "runtime error: " + string(r) }
// A Type is a symbolic representation of a Lua VM type.
type Type int
// Valid Type values.
const (
TypeNil Type = iota
TypeBoolean
TypeLightUserData
TypeNumber
TypeString
TypeTable
TypeFunction
TypeUserData
TypeThread
TypeCount
TypeNone = TypeNil - 1
)
// An Operator is an op argument for Arith.
type Operator int
// Valid Operator values for Arith.
const (
OpAdd Operator = iota // Performs addition (+).
OpSub // Performs subtraction (-).
OpMul // Performs multiplication (*).
OpDiv // Performs division (/).
OpMod // Performs modulo (%).
OpPow // Performs exponentiation (^).
OpUnaryMinus // Performs mathematical negation (unary -).
)
// A ComparisonOperator is an op argument for Compare.
type ComparisonOperator int
// Valid ComparisonOperator values for Compare.
const (
OpEq ComparisonOperator = iota // Compares for equality (==).
OpLT // Compares for less than (<).
OpLE // Compares for less or equal (<=).
)
// Lua provides a registry, a predefined table, that can be used by any Go code
// to store whatever Lua values it needs to store. The registry table is always
// located at pseudo-index RegistryIndex, which is a valid index. Any Go
// library can store data into this table, but it should take care to choose
// keys that are different from those used by other libraries, to avoid
// collisions. Typically, you should use as key a string containing your
// library name, or a light userdata object in your code, or any Lua object
// created by your code. As with global names, string keys starting with an
// underscore followed by uppercase letters are reserved for Lua.
//
// The integer keys in the registry are used by the reference mechanism
// and by some predefined values. Therefore, integer keys should not be used
// for other purposes.
//
// When you create a new Lua state, its registry comes with some predefined
// values. These predefined values are indexed with integer keys defined as
// constants.
const (
// RegistryIndex is the pseudo-index for the registry table.
RegistryIndex = firstPseudoIndex
// RegistryIndexMainThread is the registry index for the main thread of the
// State. (The main thread is the one created together with the State.)
RegistryIndexMainThread = iota
// RegistryIndexGlobals is the registry index for the global environment.
RegistryIndexGlobals
)
// Signature is the mark for precompiled code ('<esc>Lua').
const Signature = "\033Lua"
// MinStack is the minimum Lua stack available to a Go function.
const MinStack = 20
const (
VersionMajor = 5
VersionMinor = 2
VersionNumber = 502
VersionString = "Lua " + string('0'+VersionMajor) + "." + string('0'+VersionMinor)
)
// A RegistryFunction is used for arrays of functions to be registered by
// SetFunctions. Name is the function name and Function is the function.
type RegistryFunction struct {
Name string
Function Function
}
// A Debug carries different pieces of information about a function or an
// activation record. Stack fills only the private part of this structure, for
// later use. To fill the other fields of a Debug with useful information, call
// Info.
type Debug struct {
Event int
// Name is a reasonable name for the given function. Because functions in
// Lua are first-class values, they do not have a fixed name. Some functions
// can be the value of multiple global variables, while others can be stored
// only in a table field. The Info function checks how the function was
// called to find a suitable name. If it cannot find a name, then Name is "".
Name string
// NameKind explains the name field. The value of NameKind can be "global",
// "local", "method", "field", "upvalue", or "" (the empty string), according
// to how the function was called. (Lua uses the empty string when no other
// option seems to apply.)
NameKind string
// What is the string "Lua" if the function is a Lua function, "Go" if it is
// a Go function, "main" if it is the main part of a chunk.
What string
// Source is the source of the chunk that created the function. If Source
// starts with a '@', it means that the function was defined in a file where
// the file name follows the '@'. If Source starts with a '=', the remainder
// of its contents describe the source in a user-dependent manner. Otherwise,
// the function was defined in a string where Source is that string.
Source string
// ShortSource is a "printable" version of source, to be used in error messages.
ShortSource string
// CurrentLine is the current line where the given function is executing.
// When no line information is available, CurrentLine is set to -1.
CurrentLine int
// LineDefined is the line number where the definition of the function starts.
LineDefined int
// LastLineDefined is the line number where the definition of the function ends.
LastLineDefined int
// UpValueCount is the number of upvalues of the function.
UpValueCount int
// ParameterCount is the number of fixed parameters of the function (always 0
// for Go functions).
ParameterCount int
// IsVarArg is true if the function is a vararg function (always true for Go
// functions).
IsVarArg bool
// IsTailCall is true if this function invocation was called by a tail call.
// In this case, the caller of this level is not in the stack.
IsTailCall bool
// callInfo is the active function.
callInfo *callInfo
}
// A Hook is a callback function that can be registered with SetDebugHook to trace various VM events.
type Hook func(state *State, activationRecord Debug)
// A Function is a Go function intended to be called from Lua.
type Function func(state *State) int
// TODO XMove(from, to State, n int)
//
// Set functions (stack -> Lua)
// RawSetValue(index int, p interface{})
//
// Debug API
// Local(activationRecord *Debug, index int) string
// SetLocal(activationRecord *Debug, index int) string
type pc int
type callStatus byte
const (
callStatusLua callStatus = 1 << iota // call is running a Lua function
callStatusHooked // call is running a debug hook
callStatusReentry // call is running on same invocation of execute of previous call
callStatusYielded // call reentered after suspension
callStatusYieldableProtected // call is a yieldable protected call
callStatusError // call has an error status (pcall)
callStatusTail // call was tail called
callStatusHookYielded // last hook called yielded
)
// A State is an opaque structure representing per thread Lua state.
type State struct {
error error
shouldYield bool
top int // first free slot in the stack
global *globalState
callInfo *callInfo // call info for current function
oldPC pc // last pC traced
stackLast int // last free slot in the stack
stack []value
nonYieldableCallCount int
nestedGoCallCount int
hookMask byte
allowHook bool
internalHook bool
baseHookCount int
hookCount int
hooker Hook
upValues *openUpValue
errorFunction int // current error handling function (stack index)
baseCallInfo callInfo // callInfo for first level (go calling lua)
protectFunction func()
}
type globalState struct {
mainThread *State
tagMethodNames [tmCount]string
metaTables [TypeCount]*table // metatables for basic types
registry *table
panicFunction Function // to be called in unprotected errors
version *float64 // pointer to version number
memoryErrorMessage string
// seed uint // randomized seed for hashes
// upValueHead upValue // head of double-linked list of all open upvalues
}
func (g *globalState) metaTable(o value) *table {
var t Type
switch o.(type) {
case nil:
t = TypeNil
case bool:
t = TypeBoolean
// TODO TypeLightUserData
case float64:
t = TypeNumber
case string:
t = TypeString
case *table:
t = TypeTable
case *goFunction:
t = TypeFunction
case closure:
t = TypeFunction
case *userData:
t = TypeUserData
case *State:
t = TypeThread
default:
return nil
}
return g.metaTables[t]
}
func (l *State) adjustResults(resultCount int) {
if resultCount == MultipleReturns && l.callInfo.top < l.top {
l.callInfo.setTop(l.top)
}
}
func (l *State) apiIncrementTop() {
l.top++
if apiCheck && l.top > l.callInfo.top {
panic("stack overflow")
}
}
func (l *State) apiPush(v value) {
l.push(v)
if apiCheck && l.top > l.callInfo.top {
panic("stack overflow")
}
}
func (l *State) checkElementCount(n int) {
if apiCheck && n >= l.top-l.callInfo.function {
panic("not enough elements in the stack")
}
}
func (l *State) checkResults(argCount, resultCount int) {
if apiCheck && resultCount != MultipleReturns && l.callInfo.top-l.top < resultCount-argCount {
panic("results from function overflow current stack size")
}
}
// Context is called by a continuation function to retrieve the status of the
// thread and context information. When called in the origin function, it
// will always return (0, false, nil). When called inside a continuation function,
// it will return (ctx, shouldYield, err), where ctx is the value that was
// passed to the callee together with the continuation function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_getctx
func (l *State) Context() (int, bool, error) {
if l.callInfo.isCallStatus(callStatusYielded) {
return l.callInfo.context, l.callInfo.shouldYield, l.callInfo.error
}
return 0, false, nil
}
// CallWithContinuation is exactly like Call, but allows the called function to
// yield.
//
// http://www.lua.org/manual/5.2/manual.html#lua_callk
func (l *State) CallWithContinuation(argCount, resultCount, context int, continuation Function) {
if apiCheck && continuation != nil && l.callInfo.isLua() {
panic("cannot use continuations inside hooks")
}
l.checkElementCount(argCount + 1)
if apiCheck && l.shouldYield {
panic("cannot do calls on non-normal thread")
}
l.checkResults(argCount, resultCount)
f := l.top - (argCount + 1)
if continuation != nil && l.nonYieldableCallCount == 0 { // need to prepare continuation?
l.callInfo.continuation = continuation
l.callInfo.context = context
l.call(f, resultCount, true) // just do the call
} else { // no continuation or not yieldable
l.call(f, resultCount, false) // just do the call
}
l.adjustResults(resultCount)
}
// ProtectedCall calls a function in protected mode. Both argCount and
// resultCount have the same meaning as in Call. If there are no errors
// during the call, ProtectedCall behaves exactly like Call.
//
// However, if there is any error, ProtectedCall catches it, pushes a single
// value on the stack (the error message), and returns an error. Like Call,
// ProtectedCall always removes the function and its arguments from the stack.
//
// If errorFunction is 0, then the error message returned on the stack is
// exactly the original error message. Otherwise, errorFunction is the stack
// index of an error handler (in the Lua C, message handler). This cannot be
// a pseudo-index in the current implementation. In case of runtime errors,
// this function will be called with the error message and its return value
// will be the message returned on the stack by ProtectedCall.
//
// Typically, the error handler is used to add more debug information to the
// error message, such as a stack traceback. Such information cannot be
// gathered after the return of ProtectedCall, since by then, the stack has
// unwound.
//
// The possible errors are the following:
//
// RuntimeError a runtime error
// MemoryError allocating memory, the error handler is not called
// ErrorError running the error handler
//
// http://www.lua.org/manual/5.2/manual.html#lua_pcall
func (l *State) ProtectedCall(argCount, resultCount, errorFunction int) error {
return l.ProtectedCallWithContinuation(argCount, resultCount, errorFunction, 0, nil)
}
// ProtectedCallWithContinuation behaves exactly like ProtectedCall, but
// allows the called function to yield.
//
// http://www.lua.org/manual/5.2/manual.html#lua_pcallk
func (l *State) ProtectedCallWithContinuation(argCount, resultCount, errorFunction, context int, continuation Function) (err error) {
if apiCheck && continuation != nil && l.callInfo.isLua() {
panic("cannot use continuations inside hooks")
}
l.checkElementCount(argCount + 1)
if apiCheck && l.shouldYield {
panic("cannot do calls on non-normal thread")
}
l.checkResults(argCount, resultCount)
if errorFunction != 0 {
apiCheckStackIndex(errorFunction, l.indexToValue(errorFunction))
errorFunction = l.AbsIndex(errorFunction)
}
f := l.top - (argCount + 1)
if continuation == nil || l.nonYieldableCallCount > 0 {
err = l.protectedCall(func() { l.call(f, resultCount, false) }, f, errorFunction)
} else {
c := l.callInfo
c.continuation, c.context, c.extra, c.oldAllowHook, c.oldErrorFunction = continuation, context, f, l.allowHook, l.errorFunction
l.errorFunction = errorFunction
l.callInfo.setCallStatus(callStatusYieldableProtected)
l.call(f, resultCount, true)
l.callInfo.clearCallStatus(callStatusYieldableProtected)
l.errorFunction = c.oldErrorFunction
}
l.adjustResults(resultCount)
return
}
// Load loads a Lua chunk, without running it. If there are no errors, it
// pushes the compiled chunk as a Lua function on top of the stack.
// Otherwise, it pushes an error message.
//
// http://www.lua.org/manual/5.2/manual.html#lua_load
func (l *State) Load(r io.Reader, chunkName string, mode string) error {
if chunkName == "" {
chunkName = "?"
}
if err := protectedParser(l, r, chunkName, mode); err != nil {
return err
}
if f := l.stack[l.top-1].(*luaClosure); f.upValueCount() == 1 {
f.setUpValue(0, l.global.registry.atInt(RegistryIndexGlobals))
}
return nil
}
// Dump dumps a function as a binary chunk. It receives a Lua function on
// the top of the stack and produces a binary chunk that, if loaded again,
// results in a function equivalent to the one dumped.
//
// http://www.lua.org/manual/5.3/manual.html#lua_dump
func (l *State) Dump(w io.Writer) error {
l.checkElementCount(1)
if f, ok := l.stack[l.top-1].(*luaClosure); ok {
return l.dump(f.prototype, w)
}
panic("closure expected")
}
// NewState creates a new thread running in a new, independent state.
//
// http://www.lua.org/manual/5.2/manual.html#lua_newstate
func NewState() *State {
v := float64(VersionNumber)
l := &State{allowHook: true, error: nil, nonYieldableCallCount: 1}
g := &globalState{mainThread: l, registry: newTable(), version: &v, memoryErrorMessage: "not enough memory"}
l.global = g
l.initializeStack()
g.registry.putAtInt(RegistryIndexMainThread, l)
g.registry.putAtInt(RegistryIndexGlobals, newTable())
copy(g.tagMethodNames[:], eventNames)
return l
}
func apiCheckStackIndex(index int, v value) {
if apiCheck && (v == none || isPseudoIndex(index)) {
panic(fmt.Sprintf("index %d not in the stack", index))
}
}
// SetField does the equivalent of table[key]=v where table is the value at
// index and v is the value on top of the stack.
//
// This function pops the value from the stack. As in Lua, this function may
// trigger a metamethod for the __newindex event.
//
// http://www.lua.org/manual/5.2/manual.html#lua_setfield
func (l *State) SetField(index int, key string) {
l.checkElementCount(1)
t := l.indexToValue(index)
l.push(key)
l.setTableAt(t, key, l.stack[l.top-2])
l.top -= 2
}
var none value = &struct{}{}
func (l *State) indexToValue(index int) value {
switch {
case index > 0:
// TODO apiCheck(index <= callInfo.top_-(callInfo.function+1), "unacceptable index")
// if i := callInfo.function + index; i < l.top {
// return l.stack[i]
// }
// return none
if l.callInfo.function+index >= l.top {
return none
}
return l.stack[l.callInfo.function:l.top][index]
case index > RegistryIndex: // negative index
// TODO apiCheck(index != 0 && -index <= l.top-(callInfo.function+1), "invalid index")
return l.stack[l.top+index]
case index == RegistryIndex:
return l.global.registry
default: // upvalues
i := RegistryIndex - index
return l.stack[l.callInfo.function].(*goClosure).upValues[i-1]
// if closure := l.stack[callInfo.function].(*goClosure); i <= len(closure.upValues) {
// return closure.upValues[i-1]
// }
// return none
}
}
func (l *State) setIndexToValue(index int, v value) {
switch {
case index > 0:
l.stack[l.callInfo.function:l.top][index] = v
// if i := callInfo.function + index; i < l.top {
// l.stack[i] = v
// } else {
// panic("unacceptable index")
// }
case index > RegistryIndex: // negative index
l.stack[l.top+index] = v
case index == RegistryIndex:
l.global.registry = v.(*table)
default: // upvalues
i := RegistryIndex - index
l.stack[l.callInfo.function].(*goClosure).upValues[i-1] = v
}
}
// AbsIndex converts the acceptable index index to an absolute index (that
// is, one that does not depend on the stack top).
//
// http://www.lua.org/manual/5.2/manual.html#lua_absindex
func (l *State) AbsIndex(index int) int {
if index > 0 || isPseudoIndex(index) {
return index
}
return l.top - l.callInfo.function + index
}
// SetTop accepts any index, or 0, and sets the stack top to 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.
//
// If index is negative, the stack will be decremented by that much. If
// the decrement is larger than the stack, SetTop will panic().
//
// http://www.lua.org/manual/5.2/manual.html#lua_settop
func (l *State) SetTop(index int) {
f := l.callInfo.function
if index >= 0 {
if apiCheck && index > l.stackLast-(f+1) {
panic("new top too large")
}
i := l.top
for l.top = f + 1 + index; i < l.top; i++ {
l.stack[i] = nil
}
} else {
if apiCheck && -(index+1) > l.top-(f+1) {
panic("invalid new top")
}
l.top += index + 1 // 'subtract' index (index is negative)
}
}
// Remove the element at the given valid index, shifting down the elements
// above index to fill the gap. This function cannot be called with a
// pseudo-index, because a pseudo-index is not an actual stack position.
//
// http://www.lua.org/manual/5.2/manual.html#lua_remove
func (l *State) Remove(index int) {
apiCheckStackIndex(index, l.indexToValue(index))
i := l.callInfo.function + l.AbsIndex(index)
copy(l.stack[i:l.top-1], l.stack[i+1:l.top])
l.top--
}
// Insert moves the top element into the given valid index, shifting up the
// elements above this index to open space. This function cannot be called
// with a pseudo-index, because a pseudo-index is not an actual stack position.
//
// http://www.lua.org/manual/5.2/manual.html#lua_insert
func (l *State) Insert(index int) {
apiCheckStackIndex(index, l.indexToValue(index))
i := l.callInfo.function + l.AbsIndex(index)
copy(l.stack[i+1:l.top+1], l.stack[i:l.top])
l.stack[i] = l.stack[l.top]
}
func (l *State) move(dest int, src value) { l.setIndexToValue(dest, src) }
// Replace moves the top element into the given valid index without shifting
// any element (therefore replacing the value at the given index), and then
// pops the top element.
//
// http://www.lua.org/manual/5.2/manual.html#lua_replace
func (l *State) Replace(index int) {
l.checkElementCount(1)
l.move(index, l.stack[l.top-1])
l.top--
}
// CheckStack ensures that there are at least size free stack slots in the
// stack. This call will not panic(), unlike the other Check*() functions.
//
// http://www.lua.org/manual/5.2/manual.html#lua_checkstack
func (l *State) CheckStack(size int) bool {
callInfo := l.callInfo
ok := l.stackLast-l.top > size
if !ok && l.top+extraStack <= maxStack-size {
ok = l.protect(func() { l.growStack(size) }) == nil
}
if ok && callInfo.top < l.top+size {
callInfo.setTop(l.top + size)
}
return ok
}
// AtPanic sets a new panic function and returns the old one.
func AtPanic(l *State, panicFunction Function) Function {
panicFunction, l.global.panicFunction = l.global.panicFunction, panicFunction
return panicFunction
}
func (l *State) valueToType(v value) Type {
switch v.(type) {
case nil:
return TypeNil
case bool:
return TypeBoolean
// case lightUserData:
// return TypeLightUserData
case float64:
return TypeNumber
case string:
return TypeString
case *table:
return TypeTable
case *goFunction:
return TypeFunction
case *userData:
return TypeUserData
case *State:
return TypeThread
case *luaClosure:
return TypeFunction
case *goClosure:
return TypeFunction
}
return TypeNone
}
// TypeOf returns the type of the value at index, or TypeNone for a
// non-valid (but acceptable) index.
//
// http://www.lua.org/manual/5.2/manual.html#lua_type
func (l *State) TypeOf(index int) Type {
return l.valueToType(l.indexToValue(index))
}
// IsGoFunction verifies that the value at index is a Go function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_iscfunction
func (l *State) IsGoFunction(index int) bool {
if _, ok := l.indexToValue(index).(*goFunction); ok {
return true
}
_, ok := l.indexToValue(index).(*goClosure)
return ok
}
// IsNumber verifies that the value at index is a number.
//
// http://www.lua.org/manual/5.2/manual.html#lua_isnumber
func (l *State) IsNumber(index int) bool {
_, ok := l.toNumber(l.indexToValue(index))
return ok
}
// IsString verifies that the value at index is a string, or a number (which
// is always convertible to a string).
//
// http://www.lua.org/manual/5.2/manual.html#lua_isstring
func (l *State) IsString(index int) bool {
if _, ok := l.indexToValue(index).(string); ok {
return true
}
_, ok := l.indexToValue(index).(float64)
return ok
}
// IsUserData verifies that the value at index is a userdata.
//
// http://www.lua.org/manual/5.2/manual.html#lua_isuserdata
func (l *State) IsUserData(index int) bool {
_, ok := l.indexToValue(index).(*userData)
return ok
}
// Arith performs an arithmetic operation over the two values (or one, in
// case of negation) at the top of the stack, with the value at the top being
// the second operand, ops these values and pushes the result of the operation.
// The function follows the semantics of the corresponding Lua operator
// (that is, it may call metamethods).
//
// http://www.lua.org/manual/5.2/manual.html#lua_arith
func (l *State) Arith(op Operator) {
if op != OpUnaryMinus {
l.checkElementCount(2)
} else {
l.checkElementCount(1)
l.push(l.stack[l.top-1])
}
o1, o2 := l.stack[l.top-2], l.stack[l.top-1]
if n1, n2, ok := pairAsNumbers(o1, o2); ok {
l.stack[l.top-2] = arith(op, n1, n2)
} else {
l.stack[l.top-2] = l.arith(o1, o2, tm(op-OpAdd)+tmAdd)
}
l.top--
}
// RawEqual verifies that the values at index1 and index2 are primitively
// equal (that is, without calling their metamethods).
//
// http://www.lua.org/manual/5.2/manual.html#lua_rawequal
func (l *State) RawEqual(index1, index2 int) bool {
if o1, o2 := l.indexToValue(index1), l.indexToValue(index2); o1 != nil && o2 != nil {
return o1 == o2
}
return false
}
// Compare compares two values.
//
// http://www.lua.org/manual/5.2/manual.html#lua_compare
func (l *State) Compare(index1, index2 int, op ComparisonOperator) bool {
if o1, o2 := l.indexToValue(index1), l.indexToValue(index2); o1 != nil && o2 != nil {
switch op {
case OpEq:
return l.equalObjects(o1, o2)
case OpLT:
return l.lessThan(o1, o2)
case OpLE:
return l.lessOrEqual(o1, o2)
default:
panic("invalid option")
}
}
return false
}
// ToInteger converts the Lua value at index into a signed integer. The Lua
// value must be a number, or a string convertible to a number.
//
// If the number is not an integer, it is truncated in some non-specified way.
//
// If the operation failed, the second return value will be false.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tointegerx
func (l *State) ToInteger(index int) (int, bool) {
if n, ok := l.toNumber(l.indexToValue(index)); ok {
return int(n), true
}
return 0, false
}
// ToUnsigned converts the Lua value at index to a Go uint. The Lua value
// must be a number or a string convertible to a number.
//
// If the number is not an unsigned integer, it is truncated in some
// non-specified way. If the number is outside the range of uint, it is
// normalized to the remainder of its division by one more than the maximum
// representable value.
//
// If the operation failed, the second return value will be false.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tounsignedx
func (l *State) ToUnsigned(index int) (uint, bool) {
if n, ok := l.toNumber(l.indexToValue(index)); ok {
const supUnsigned = float64(^uint32(0)) + 1
return uint(n - math.Floor(n/supUnsigned)*supUnsigned), true
}
return 0, false
}
// ToString converts the Lua value at index to a Go string. The Lua value
// must also be a string or a number; otherwise the function returns
// false for its second return value.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tolstring
func (l *State) ToString(index int) (s string, ok bool) {
if s, ok = toString(l.indexToValue(index)); ok { // Bug compatibility: replace a number with its string representation.
l.setIndexToValue(index, s)
}
return
}
// RawLength returns the length of the value at index. For strings, this is
// the length. For tables, this is the result of the # operator with no
// metamethods. For userdata, this is the size of the block of memory
// allocated for the userdata (not implemented yet). For other values, it is 0.
//
// http://www.lua.org/manual/5.2/manual.html#lua_rawlen
func (l *State) RawLength(index int) int {
switch v := l.indexToValue(index).(type) {
case string:
return len(v)
// case *userData:
// return reflect.Sizeof(v.data)
case *table:
return v.length()
}
return 0
}
// ToGoFunction converts a value at index into a Go function. That value
// must be a Go function, otherwise it returns nil.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tocfunction
func (l *State) ToGoFunction(index int) Function {
switch v := l.indexToValue(index).(type) {
case *goFunction:
return v.Function
case *goClosure:
return v.function
}
return nil
}
// ToUserData returns an interface{} of the userdata of the value at index.
// Otherwise, it returns nil.
//
// http://www.lua.org/manual/5.2/manual.html#lua_touserdata
func (l *State) ToUserData(index int) interface{} {
if d, ok := l.indexToValue(index).(*userData); ok {
return d.data
}
return nil
}
// ToThread converts the value at index to a Lua thread (a State). This
// value must be a thread, otherwise the return value will be nil.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tothread
func (l *State) ToThread(index int) *State {
if t, ok := l.indexToValue(index).(*State); ok {
return t
}
return nil
}
// ToValue convertes the value at index into a generic Go interface{}. The
// value can be a userdata, a table, a thread, a function, or Go string, bool
// or float64 types. Otherwise, the function returns nil.
//
// Different objects will give different values. There is no way to convert
// the value back into its original value.
//
// Typically, this function is used only for debug information.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tovalue
func (l *State) ToValue(index int) interface{} {
v := l.indexToValue(index)
switch v := v.(type) {
case string, float64, bool, *table, *luaClosure, *goClosure, *goFunction, *State:
case *userData:
return v.data
default:
return nil
}
return v
}
// PushString pushes a string onto the stack.
//
// http://www.lua.org/manual/5.2/manual.html#lua_pushstring
func (l *State) PushString(s string) string { // TODO is it useful to return the argument?
l.apiPush(s)
return s
}
// PushFString pushes onto the stack a formatted string and returns that
// string. It is similar to fmt.Sprintf, but has some differences: the
// conversion specifiers are quite restricted. There are no flags, widths,
// or precisions. The conversion specifiers can only be %% (inserts a %
// in the string), %s, %f (a Lua number), %p (a pointer as a hexadecimal
// numeral), %d and %c (an integer as a byte).
//
// http://www.lua.org/manual/5.2/manual.html#lua_pushfstring
func (l *State) PushFString(format string, args ...interface{}) string {
n, i := 0, 0
for {
e := strings.IndexRune(format, '%')
if e < 0 {
break
}
l.checkStack(2) // format + item
l.push(format[:e])
switch format[e+1] {
case 's':
if args[i] == nil {
l.push("(null)")
} else {
l.push(args[i].(string))
}
i++
case 'c':
l.push(string(args[i].(rune)))
i++
case 'd':
l.push(float64(args[i].(int)))
i++
case 'f':
l.push(args[i].(float64))
i++
case 'p':
l.push(fmt.Sprintf("%p", args[i]))
i++
case '%':
l.push("%")
default:
l.runtimeError("invalid option " + format[e:e+2] + " to 'lua_pushfstring'")
}
n += 2
format = format[e+2:]
}
l.checkStack(1)
l.push(format)
if n > 0 {
l.concat(n + 1)
}
return l.stack[l.top-1].(string)
}
// PushGoClosure pushes a new Go closure onto the stack.
//
// When a Go function is created, it is possible to associate some values with
// it, thus creating a Go closure; these values are then accessible to the
// function whenever it is called. To associate values with a Go function,
// first these values should be pushed onto the stack (when there are multiple
// values, the first value is pushed first). Then PushGoClosure is called to
// create and push the Go function onto the stack, with the argument upValueCount
// telling how many values should be associated with the function. Calling
// PushGoClosure also pops these values from the stack.
//
// When upValueCount is 0, this function creates a light Go function, which is just a
// Go function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_pushcclosure
func (l *State) PushGoClosure(function Function, upValueCount uint8) {
if upValueCount == 0 {
l.apiPush(&goFunction{function})
} else {
n := int(upValueCount)
l.checkElementCount(n)
cl := &goClosure{function: function, upValues: make([]value, upValueCount)}
l.top -= n
copy(cl.upValues, l.stack[l.top:l.top+n])
l.apiPush(cl)
}
}
// PushThread pushes the thread l onto the stack. It returns true if l is
// the main thread of its state.
//
// http://www.lua.org/manual/5.2/manual.html#lua_pushthread
func (l *State) PushThread() bool {
l.apiPush(l)
return l.global.mainThread == l
}
// Global pushes onto the stack the value of the global name.
//
// http://www.lua.org/manual/5.2/manual.html#lua_getglobal
func (l *State) Global(name string) {
g := l.global.registry.atInt(RegistryIndexGlobals)
l.push(name)
l.stack[l.top-1] = l.tableAt(g, l.stack[l.top-1])
}
// Field pushes onto the stack the value table[name], where table is the
// table on the stack at the given index. This call may trigger a
// metamethod for the __index event.
//
// http://www.lua.org/manual/5.2/manual.html#lua_getfield
func (l *State) Field(index int, name string) {
t := l.indexToValue(index)
l.apiPush(name)
l.stack[l.top-1] = l.tableAt(t, l.stack[l.top-1])
}