_state.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. package lua
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/vmihailenco/msgpack"
  6. "github.com/yuin/gopher-lua/parse"
  7. "golang.org/x/net/context"
  8. "io"
  9. "io/ioutil"
  10. "math"
  11. "os"
  12. "runtime"
  13. "strings"
  14. "sync/atomic"
  15. "time"
  16. )
  17. const MultRet = -1
  18. const RegistryIndex = -10000
  19. const EnvironIndex = -10001
  20. const GlobalsIndex = -10002
  21. /* ApiError {{{ */
  22. type ApiError struct {
  23. Type ApiErrorType
  24. Object LValue
  25. StackTrace string
  26. // Underlying error. This attribute is set only if the Type is ApiErrorFile or ApiErrorSyntax
  27. Cause error
  28. }
  29. func newApiError(code ApiErrorType, object LValue) *ApiError {
  30. return &ApiError{code, object, "", nil}
  31. }
  32. func newApiErrorS(code ApiErrorType, message string) *ApiError {
  33. return newApiError(code, LString(message))
  34. }
  35. func newApiErrorE(code ApiErrorType, err error) *ApiError {
  36. return &ApiError{code, LString(err.Error()), "", err}
  37. }
  38. func (e *ApiError) Error() string {
  39. if len(e.StackTrace) > 0 {
  40. return fmt.Sprintf("%s\n%s", e.Object.String(), e.StackTrace)
  41. }
  42. return e.Object.String()
  43. }
  44. type ApiErrorType int
  45. const (
  46. ApiErrorSyntax ApiErrorType = iota
  47. ApiErrorFile
  48. ApiErrorRun
  49. ApiErrorError
  50. ApiErrorPanic
  51. )
  52. /* }}} */
  53. /* ResumeState {{{ */
  54. type ResumeState int
  55. const (
  56. ResumeOK ResumeState = iota
  57. ResumeYield
  58. ResumeError
  59. )
  60. /* }}} */
  61. /* P {{{ */
  62. type P struct {
  63. Fn LValue
  64. NRet int
  65. Protect bool
  66. Handler *LFunction
  67. }
  68. /* }}} */
  69. /* Options {{{ */
  70. // Options is a configuration that is used to create a new LState.
  71. type Options struct {
  72. // Call stack size. This defaults to `lua.CallStackSize`.
  73. CallStackSize int
  74. // Data stack size. This defaults to `lua.RegistrySize`.
  75. RegistrySize int
  76. // Controls whether or not libraries are opened by default
  77. SkipOpenLibs bool
  78. // Tells whether a Go stacktrace should be included in a Lua stacktrace when panics occur.
  79. IncludeGoStackTrace bool
  80. }
  81. /* }}} */
  82. /* Debug {{{ */
  83. type Debug struct {
  84. frame *callFrame
  85. Name string
  86. What string
  87. Source string
  88. CurrentLine int
  89. NUpvalues int
  90. LineDefined int
  91. LastLineDefined int
  92. }
  93. /* }}} */
  94. /* callFrame {{{ */
  95. type callFrame struct {
  96. Idx int
  97. Fn *LFunction
  98. Parent *callFrame
  99. Pc int
  100. Base int
  101. LocalBase int
  102. ReturnBase int
  103. NArgs int
  104. NRet int
  105. TailCall int
  106. }
  107. type callFrameStack struct {
  108. array []callFrame
  109. sp int
  110. }
  111. func newCallFrameStack(size int) *callFrameStack {
  112. return &callFrameStack{
  113. array: make([]callFrame, size),
  114. sp: 0,
  115. }
  116. }
  117. func (cs *callFrameStack) IsEmpty() bool { return cs.sp == 0 }
  118. func (cs *callFrameStack) Clear() {
  119. cs.sp = 0
  120. }
  121. func (cs *callFrameStack) Push(v callFrame) { // +inline-start
  122. cs.array[cs.sp] = v
  123. cs.array[cs.sp].Idx = cs.sp
  124. cs.sp++
  125. } // +inline-end
  126. func (cs *callFrameStack) Remove(sp int) {
  127. psp := sp - 1
  128. nsp := sp + 1
  129. var pre *callFrame
  130. var next *callFrame
  131. if psp > 0 {
  132. pre = &cs.array[psp]
  133. }
  134. if nsp < cs.sp {
  135. next = &cs.array[nsp]
  136. }
  137. if next != nil {
  138. next.Parent = pre
  139. }
  140. for i := sp; i+1 < cs.sp; i++ {
  141. cs.array[i] = cs.array[i+1]
  142. cs.array[i].Idx = i
  143. cs.sp = i
  144. }
  145. cs.sp++
  146. }
  147. func (cs *callFrameStack) Sp() int {
  148. return cs.sp
  149. }
  150. func (cs *callFrameStack) SetSp(sp int) {
  151. cs.sp = sp
  152. }
  153. func (cs *callFrameStack) Last() *callFrame {
  154. if cs.sp == 0 {
  155. return nil
  156. }
  157. return &cs.array[cs.sp-1]
  158. }
  159. func (cs *callFrameStack) At(sp int) *callFrame {
  160. return &cs.array[sp]
  161. }
  162. func (cs *callFrameStack) Pop() *callFrame {
  163. cs.sp--
  164. return &cs.array[cs.sp]
  165. }
  166. /* }}} */
  167. /* registry {{{ */
  168. type registry struct {
  169. array []LValue
  170. top int
  171. alloc *allocator
  172. }
  173. func newRegistry(size int, alloc *allocator) *registry {
  174. return &registry{make([]LValue, size), 0, alloc}
  175. }
  176. func (rg *registry) SetTop(top int) {
  177. oldtop := rg.top
  178. rg.top = top
  179. for i := oldtop; i < rg.top; i++ {
  180. rg.array[i] = LNil
  181. }
  182. for i := rg.top; i < oldtop; i++ {
  183. rg.array[i] = LNil
  184. }
  185. }
  186. func (rg *registry) Top() int {
  187. return rg.top
  188. }
  189. func (rg *registry) Push(v LValue) {
  190. rg.array[rg.top] = v
  191. rg.top++
  192. }
  193. func (rg *registry) Pop() LValue {
  194. v := rg.array[rg.top-1]
  195. rg.array[rg.top-1] = LNil
  196. rg.top--
  197. return v
  198. }
  199. func (rg *registry) Get(reg int) LValue {
  200. return rg.array[reg]
  201. }
  202. func (rg *registry) CopyRange(regv, start, limit, n int) { // +inline-start
  203. for i := 0; i < n; i++ {
  204. if tidx := start + i; tidx >= rg.top || limit > -1 && tidx >= limit || tidx < 0 {
  205. rg.array[regv+i] = LNil
  206. } else {
  207. rg.array[regv+i] = rg.array[tidx]
  208. }
  209. }
  210. rg.top = regv + n
  211. } // +inline-end
  212. func (rg *registry) FillNil(regm, n int) { // +inline-start
  213. for i := 0; i < n; i++ {
  214. rg.array[regm+i] = LNil
  215. }
  216. rg.top = regm + n
  217. } // +inline-end
  218. func (rg *registry) Insert(value LValue, reg int) {
  219. top := rg.Top()
  220. if reg >= top {
  221. rg.Set(reg, value)
  222. return
  223. }
  224. top--
  225. for ; top >= reg; top-- {
  226. rg.Set(top+1, rg.Get(top))
  227. }
  228. rg.Set(reg, value)
  229. }
  230. func (rg *registry) Set(reg int, val LValue) {
  231. rg.array[reg] = val
  232. if reg >= rg.top {
  233. rg.top = reg + 1
  234. }
  235. }
  236. func (rg *registry) SetNumber(reg int, val LNumber) {
  237. rg.array[reg] = rg.alloc.LNumber2I(val)
  238. if reg >= rg.top {
  239. rg.top = reg + 1
  240. }
  241. } /* }}} */
  242. /* Global {{{ */
  243. func newGlobal() *Global {
  244. return &Global{
  245. MainThread: nil,
  246. Registry: newLTable(0, 32),
  247. Global: newLTable(0, 64),
  248. builtinMts: make(map[int]LValue),
  249. tempFiles: make([]*os.File, 0, 10),
  250. }
  251. }
  252. /* }}} */
  253. /* package local methods {{{ */
  254. func panicWithTraceback(L *LState) {
  255. err := newApiError(ApiErrorRun, L.Get(-1))
  256. err.StackTrace = L.stackTrace(0)
  257. panic(err)
  258. }
  259. func panicWithoutTraceback(L *LState) {
  260. err := newApiError(ApiErrorRun, L.Get(-1))
  261. panic(err)
  262. }
  263. func newLState(options Options) *LState {
  264. al := newAllocator(32)
  265. ls := &LState{
  266. G: newGlobal(),
  267. Parent: nil,
  268. Panic: panicWithTraceback,
  269. Dead: false,
  270. Options: options,
  271. stop: 0,
  272. reg: newRegistry(options.RegistrySize, al),
  273. stack: newCallFrameStack(options.CallStackSize),
  274. alloc: al,
  275. currentFrame: nil,
  276. wrapped: false,
  277. uvcache: nil,
  278. hasErrorFunc: false,
  279. mainLoop: mainLoop,
  280. ctx: nil,
  281. }
  282. ls.Env = ls.G.Global
  283. return ls
  284. }
  285. func (ls *LState) printReg() {
  286. println("-------------------------")
  287. println("thread:", ls)
  288. println("top:", ls.reg.Top())
  289. if ls.currentFrame != nil {
  290. println("function base:", ls.currentFrame.Base)
  291. println("return base:", ls.currentFrame.ReturnBase)
  292. } else {
  293. println("(vm not started)")
  294. }
  295. println("local base:", ls.currentLocalBase())
  296. for i := 0; i < ls.reg.Top(); i++ {
  297. println(i, ls.reg.Get(i).String())
  298. }
  299. println("-------------------------")
  300. }
  301. func (ls *LState) printCallStack() {
  302. println("-------------------------")
  303. for i := 0; i < ls.stack.Sp(); i++ {
  304. print(i)
  305. print(" ")
  306. frame := ls.stack.At(i)
  307. if frame == nil {
  308. break
  309. }
  310. if frame.Fn.IsG {
  311. println("IsG:", true, "Frame:", frame, "Fn:", frame.Fn)
  312. } else {
  313. println("IsG:", false, "Frame:", frame, "Fn:", frame.Fn, "pc:", frame.Pc)
  314. }
  315. }
  316. println("-------------------------")
  317. }
  318. func (ls *LState) closeAllUpvalues() { // +inline-start
  319. for cf := ls.currentFrame; cf != nil; cf = cf.Parent {
  320. if !cf.Fn.IsG {
  321. ls.closeUpvalues(cf.LocalBase)
  322. }
  323. }
  324. } // +inline-end
  325. func (ls *LState) raiseError(level int, format string, args ...interface{}) {
  326. if !ls.hasErrorFunc {
  327. ls.closeAllUpvalues()
  328. }
  329. message := format
  330. if len(args) > 0 {
  331. message = fmt.Sprintf(format, args...)
  332. }
  333. if level > 0 {
  334. message = fmt.Sprintf("%v %v", ls.where(level-1, true), message)
  335. }
  336. ls.reg.Push(LString(message))
  337. ls.Panic(ls)
  338. }
  339. func (ls *LState) findLocal(frame *callFrame, no int) string {
  340. fn := frame.Fn
  341. if !fn.IsG {
  342. if name, ok := fn.LocalName(no, frame.Pc-1); ok {
  343. return name
  344. }
  345. }
  346. var top int
  347. if ls.currentFrame == frame {
  348. top = ls.reg.Top()
  349. } else if frame.Idx+1 < ls.stack.Sp() {
  350. top = ls.stack.At(frame.Idx + 1).Base
  351. } else {
  352. return ""
  353. }
  354. if top-frame.LocalBase >= no {
  355. return "(*temporary)"
  356. }
  357. return ""
  358. }
  359. func (ls *LState) where(level int, skipg bool) string {
  360. dbg, ok := ls.GetStack(level)
  361. if !ok {
  362. return ""
  363. }
  364. cf := dbg.frame
  365. proto := cf.Fn.Proto
  366. sourcename := "[G]"
  367. if proto != nil {
  368. sourcename = proto.SourceName
  369. } else if skipg {
  370. return ls.where(level+1, skipg)
  371. }
  372. line := ""
  373. if proto != nil {
  374. line = fmt.Sprintf("%v:", proto.DbgSourcePositions[cf.Pc-1])
  375. }
  376. return fmt.Sprintf("%v:%v", sourcename, line)
  377. }
  378. func (ls *LState) stackTrace(level int) string {
  379. buf := []string{}
  380. header := "stack traceback:"
  381. if ls.currentFrame != nil {
  382. i := 0
  383. for dbg, ok := ls.GetStack(i); ok; dbg, ok = ls.GetStack(i) {
  384. cf := dbg.frame
  385. buf = append(buf, fmt.Sprintf("\t%v in %v", ls.Where(i), ls.formattedFrameFuncName(cf)))
  386. if !cf.Fn.IsG && cf.TailCall > 0 {
  387. for tc := cf.TailCall; tc > 0; tc-- {
  388. buf = append(buf, "\t(tailcall): ?")
  389. i++
  390. }
  391. }
  392. i++
  393. }
  394. }
  395. buf = append(buf, fmt.Sprintf("\t%v: %v", "[G]", "?"))
  396. buf = buf[intMax(0, intMin(level, len(buf))):len(buf)]
  397. if len(buf) > 20 {
  398. newbuf := make([]string, 0, 20)
  399. newbuf = append(newbuf, buf[0:7]...)
  400. newbuf = append(newbuf, "\t...")
  401. newbuf = append(newbuf, buf[len(buf)-7:len(buf)]...)
  402. buf = newbuf
  403. }
  404. return fmt.Sprintf("%s\n%s", header, strings.Join(buf, "\n"))
  405. }
  406. func (ls *LState) formattedFrameFuncName(fr *callFrame) string {
  407. name, ischunk := ls.frameFuncName(fr)
  408. if ischunk {
  409. return name
  410. }
  411. if name[0] != '(' && name[0] != '<' {
  412. return fmt.Sprintf("function '%s'", name)
  413. }
  414. return fmt.Sprintf("function %s", name)
  415. }
  416. func (ls *LState) rawFrameFuncName(fr *callFrame) string {
  417. name, _ := ls.frameFuncName(fr)
  418. return name
  419. }
  420. func (ls *LState) frameFuncName(fr *callFrame) (string, bool) {
  421. frame := fr.Parent
  422. if frame == nil {
  423. if ls.Parent == nil {
  424. return "main chunk", true
  425. } else {
  426. return "corountine", true
  427. }
  428. }
  429. if !frame.Fn.IsG {
  430. pc := frame.Pc - 1
  431. for _, call := range frame.Fn.Proto.DbgCalls {
  432. if call.Pc == pc {
  433. name := call.Name
  434. if (name == "?" || fr.TailCall > 0) && !fr.Fn.IsG {
  435. name = fmt.Sprintf("<%v:%v>", fr.Fn.Proto.SourceName, fr.Fn.Proto.LineDefined)
  436. }
  437. return name, false
  438. }
  439. }
  440. }
  441. if !fr.Fn.IsG {
  442. return fmt.Sprintf("<%v:%v>", fr.Fn.Proto.SourceName, fr.Fn.Proto.LineDefined), false
  443. }
  444. return "(anonymous)", false
  445. }
  446. func (ls *LState) isStarted() bool {
  447. return ls.currentFrame != nil
  448. }
  449. func (ls *LState) kill() {
  450. ls.Dead = true
  451. }
  452. func (ls *LState) indexToReg(idx int) int {
  453. base := ls.currentLocalBase()
  454. if idx > 0 {
  455. return base + idx - 1
  456. } else if idx == 0 {
  457. return -1
  458. } else {
  459. tidx := ls.reg.Top() + idx
  460. if tidx < base {
  461. return -1
  462. }
  463. return tidx
  464. }
  465. }
  466. func (ls *LState) currentLocalBase() int {
  467. base := 0
  468. if ls.currentFrame != nil {
  469. base = ls.currentFrame.LocalBase
  470. }
  471. return base
  472. }
  473. func (ls *LState) currentEnv() *LTable {
  474. return ls.Env
  475. /*
  476. if ls.currentFrame == nil {
  477. return ls.Env
  478. }
  479. return ls.currentFrame.Fn.Env
  480. */
  481. }
  482. func (ls *LState) rkValue(idx int) LValue {
  483. /*
  484. if OpIsK(idx) {
  485. return ls.currentFrame.Fn.Proto.Constants[opIndexK(idx)]
  486. }
  487. return ls.reg.Get(ls.currentFrame.LocalBase + idx)
  488. */
  489. if (idx & opBitRk) != 0 {
  490. return ls.currentFrame.Fn.Proto.Constants[idx & ^opBitRk]
  491. }
  492. return ls.reg.array[ls.currentFrame.LocalBase+idx]
  493. }
  494. func (ls *LState) rkString(idx int) string {
  495. if (idx & opBitRk) != 0 {
  496. return ls.currentFrame.Fn.Proto.stringConstants[idx & ^opBitRk]
  497. }
  498. return string(ls.reg.array[ls.currentFrame.LocalBase+idx].(LString))
  499. }
  500. func (ls *LState) closeUpvalues(idx int) { // +inline-start
  501. if ls.uvcache != nil {
  502. var prev *Upvalue
  503. for uv := ls.uvcache; uv != nil; uv = uv.next {
  504. if uv.index >= idx {
  505. if prev != nil {
  506. prev.next = nil
  507. } else {
  508. ls.uvcache = nil
  509. }
  510. uv.Close()
  511. }
  512. prev = uv
  513. }
  514. }
  515. } // +inline-end
  516. func (ls *LState) findUpvalue(idx int) *Upvalue {
  517. var prev *Upvalue
  518. var next *Upvalue
  519. if ls.uvcache != nil {
  520. for uv := ls.uvcache; uv != nil; uv = uv.next {
  521. if uv.index == idx {
  522. return uv
  523. }
  524. if uv.index > idx {
  525. next = uv
  526. break
  527. }
  528. prev = uv
  529. }
  530. }
  531. uv := &Upvalue{reg: ls.reg, index: idx, closed: false}
  532. if prev != nil {
  533. prev.next = uv
  534. } else {
  535. ls.uvcache = uv
  536. }
  537. if next != nil {
  538. uv.next = next
  539. }
  540. return uv
  541. }
  542. func (ls *LState) metatable(lvalue LValue, rawget bool) LValue {
  543. var metatable LValue = LNil
  544. switch obj := lvalue.(type) {
  545. case *LTable:
  546. metatable = obj.Metatable
  547. case *LUserData:
  548. metatable = obj.Metatable
  549. default:
  550. if table, ok := ls.G.builtinMts[int(obj.Type())]; ok {
  551. metatable = table
  552. }
  553. }
  554. if !rawget && metatable != LNil {
  555. oldmt := metatable
  556. if tb, ok := metatable.(*LTable); ok {
  557. metatable = tb.RawGetString("__metatable")
  558. if metatable == LNil {
  559. metatable = oldmt
  560. }
  561. }
  562. }
  563. return metatable
  564. }
  565. func (ls *LState) metaOp1(lvalue LValue, event string) LValue {
  566. if mt := ls.metatable(lvalue, true); mt != LNil {
  567. if tb, ok := mt.(*LTable); ok {
  568. return tb.RawGetString(event)
  569. }
  570. }
  571. return LNil
  572. }
  573. func (ls *LState) metaOp2(value1, value2 LValue, event string) LValue {
  574. if mt := ls.metatable(value1, true); mt != LNil {
  575. if tb, ok := mt.(*LTable); ok {
  576. if ret := tb.RawGetString(event); ret != LNil {
  577. return ret
  578. }
  579. }
  580. }
  581. if mt := ls.metatable(value2, true); mt != LNil {
  582. if tb, ok := mt.(*LTable); ok {
  583. return tb.RawGetString(event)
  584. }
  585. }
  586. return LNil
  587. }
  588. func (ls *LState) metaCall(lvalue LValue) (*LFunction, bool) {
  589. if fn, ok := lvalue.(*LFunction); ok {
  590. return fn, false
  591. }
  592. if fn, ok := ls.metaOp1(lvalue, "__call").(*LFunction); ok {
  593. return fn, true
  594. }
  595. return nil, false
  596. }
  597. func (ls *LState) initCallFrame(cf *callFrame) { // +inline-start
  598. if cf.Fn.IsG {
  599. ls.reg.SetTop(cf.LocalBase + cf.NArgs)
  600. } else {
  601. proto := cf.Fn.Proto
  602. nargs := cf.NArgs
  603. np := int(proto.NumParameters)
  604. for i := nargs; i < np; i++ {
  605. ls.reg.array[cf.LocalBase+i] = LNil
  606. nargs = np
  607. }
  608. if (proto.IsVarArg & VarArgIsVarArg) == 0 {
  609. if nargs < int(proto.NumUsedRegisters) {
  610. nargs = int(proto.NumUsedRegisters)
  611. }
  612. for i := np; i < nargs; i++ {
  613. ls.reg.array[cf.LocalBase+i] = LNil
  614. }
  615. ls.reg.top = cf.LocalBase + int(proto.NumUsedRegisters)
  616. } else {
  617. /* swap vararg positions:
  618. closure
  619. namedparam1 <- lbase
  620. namedparam2
  621. vararg1
  622. vararg2
  623. TO
  624. closure
  625. nil
  626. nil
  627. vararg1
  628. vararg2
  629. namedparam1 <- lbase
  630. namedparam2
  631. */
  632. nvarargs := nargs - np
  633. if nvarargs < 0 {
  634. nvarargs = 0
  635. }
  636. ls.reg.SetTop(cf.LocalBase + nargs + np)
  637. for i := 0; i < np; i++ {
  638. //ls.reg.Set(cf.LocalBase+nargs+i, ls.reg.Get(cf.LocalBase+i))
  639. ls.reg.array[cf.LocalBase+nargs+i] = ls.reg.array[cf.LocalBase+i]
  640. //ls.reg.Set(cf.LocalBase+i, LNil)
  641. ls.reg.array[cf.LocalBase+i] = LNil
  642. }
  643. if CompatVarArg {
  644. ls.reg.SetTop(cf.LocalBase + nargs + np + 1)
  645. if (proto.IsVarArg & VarArgNeedsArg) != 0 {
  646. argtb := newLTable(nvarargs, 0)
  647. for i := 0; i < nvarargs; i++ {
  648. argtb.RawSetInt(i+1, ls.reg.Get(cf.LocalBase+np+i))
  649. }
  650. argtb.RawSetString("n", LNumber(nvarargs))
  651. //ls.reg.Set(cf.LocalBase+nargs+np, argtb)
  652. ls.reg.array[cf.LocalBase+nargs+np] = argtb
  653. } else {
  654. ls.reg.array[cf.LocalBase+nargs+np] = LNil
  655. }
  656. }
  657. cf.LocalBase += nargs
  658. maxreg := cf.LocalBase + int(proto.NumUsedRegisters)
  659. ls.reg.SetTop(maxreg)
  660. }
  661. }
  662. } // +inline-end
  663. func (ls *LState) pushCallFrame(cf callFrame, fn LValue, meta bool) { // +inline-start
  664. if meta {
  665. cf.NArgs++
  666. ls.reg.Insert(fn, cf.LocalBase)
  667. }
  668. if cf.Fn == nil {
  669. ls.RaiseError("attempt to call a non-function object")
  670. }
  671. if ls.stack.sp == ls.Options.CallStackSize {
  672. ls.RaiseError("stack overflow")
  673. }
  674. // +inline-call ls.stack.Push cf
  675. newcf := ls.stack.Last()
  676. // +inline-call ls.initCallFrame newcf
  677. ls.currentFrame = newcf
  678. } // +inline-end
  679. func (ls *LState) callR(nargs, nret, rbase int) {
  680. base := ls.reg.Top() - nargs - 1
  681. if rbase < 0 {
  682. rbase = base
  683. }
  684. lv := ls.reg.Get(base)
  685. fn, meta := ls.metaCall(lv)
  686. ls.pushCallFrame(callFrame{
  687. Fn: fn,
  688. Pc: 0,
  689. Base: base,
  690. LocalBase: base + 1,
  691. ReturnBase: rbase,
  692. NArgs: nargs,
  693. NRet: nret,
  694. Parent: ls.currentFrame,
  695. TailCall: 0,
  696. }, lv, meta)
  697. if ls.G.MainThread == nil {
  698. ls.G.MainThread = ls
  699. ls.G.CurrentThread = ls
  700. ls.mainLoop(ls, nil)
  701. } else {
  702. ls.mainLoop(ls, ls.currentFrame)
  703. }
  704. if nret != MultRet {
  705. ls.reg.SetTop(rbase + nret)
  706. }
  707. }
  708. func (ls *LState) getField(obj LValue, key LValue) LValue {
  709. curobj := obj
  710. for i := 0; i < MaxTableGetLoop; i++ {
  711. tb, istable := curobj.(*LTable)
  712. if istable {
  713. ret := tb.RawGet(key)
  714. if ret != LNil {
  715. return ret
  716. }
  717. }
  718. metaindex := ls.metaOp1(curobj, "__index")
  719. if metaindex == LNil {
  720. if !istable {
  721. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  722. }
  723. return LNil
  724. }
  725. if metaindex.Type() == LTFunction {
  726. ls.reg.Push(metaindex)
  727. ls.reg.Push(curobj)
  728. ls.reg.Push(key)
  729. ls.Call(2, 1)
  730. return ls.reg.Pop()
  731. } else {
  732. curobj = metaindex
  733. }
  734. }
  735. ls.RaiseError("too many recursions in gettable")
  736. return nil
  737. }
  738. func (ls *LState) getFieldString(obj LValue, key string) LValue {
  739. curobj := obj
  740. for i := 0; i < MaxTableGetLoop; i++ {
  741. tb, istable := curobj.(*LTable)
  742. if istable {
  743. ret := tb.RawGetString(key)
  744. if ret != LNil {
  745. return ret
  746. }
  747. }
  748. metaindex := ls.metaOp1(curobj, "__index")
  749. if metaindex == LNil {
  750. if !istable {
  751. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  752. }
  753. return LNil
  754. }
  755. if metaindex.Type() == LTFunction {
  756. ls.reg.Push(metaindex)
  757. ls.reg.Push(curobj)
  758. ls.reg.Push(LString(key))
  759. ls.Call(2, 1)
  760. return ls.reg.Pop()
  761. } else {
  762. curobj = metaindex
  763. }
  764. }
  765. ls.RaiseError("too many recursions in gettable")
  766. return nil
  767. }
  768. func (ls *LState) setField(obj LValue, key LValue, value LValue) {
  769. curobj := obj
  770. for i := 0; i < MaxTableGetLoop; i++ {
  771. tb, istable := curobj.(*LTable)
  772. if istable {
  773. if tb.RawGet(key) != LNil {
  774. ls.RawSet(tb, key, value)
  775. return
  776. }
  777. }
  778. metaindex := ls.metaOp1(curobj, "__newindex")
  779. if metaindex == LNil {
  780. if !istable {
  781. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  782. }
  783. ls.RawSet(tb, key, value)
  784. return
  785. }
  786. if metaindex.Type() == LTFunction {
  787. ls.reg.Push(metaindex)
  788. ls.reg.Push(curobj)
  789. ls.reg.Push(key)
  790. ls.reg.Push(value)
  791. ls.Call(3, 0)
  792. return
  793. } else {
  794. curobj = metaindex
  795. }
  796. }
  797. ls.RaiseError("too many recursions in settable")
  798. }
  799. func (ls *LState) setFieldString(obj LValue, key string, value LValue) {
  800. curobj := obj
  801. for i := 0; i < MaxTableGetLoop; i++ {
  802. tb, istable := curobj.(*LTable)
  803. if istable {
  804. if tb.RawGetString(key) != LNil {
  805. tb.RawSetString(key, value)
  806. return
  807. }
  808. }
  809. metaindex := ls.metaOp1(curobj, "__newindex")
  810. if metaindex == LNil {
  811. if !istable {
  812. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  813. }
  814. tb.RawSetString(key, value)
  815. return
  816. }
  817. if metaindex.Type() == LTFunction {
  818. ls.reg.Push(metaindex)
  819. ls.reg.Push(curobj)
  820. ls.reg.Push(LString(key))
  821. ls.reg.Push(value)
  822. ls.Call(3, 0)
  823. return
  824. } else {
  825. curobj = metaindex
  826. }
  827. }
  828. ls.RaiseError("too many recursions in settable")
  829. }
  830. /* }}} */
  831. /* api methods {{{ */
  832. func NewState(opts ...Options) *LState {
  833. var ls *LState
  834. if len(opts) == 0 {
  835. ls = newLState(Options{
  836. CallStackSize: CallStackSize,
  837. RegistrySize: RegistrySize,
  838. })
  839. ls.OpenLibs()
  840. } else {
  841. if opts[0].CallStackSize < 1 {
  842. opts[0].CallStackSize = CallStackSize
  843. }
  844. if opts[0].RegistrySize < 128 {
  845. opts[0].RegistrySize = RegistrySize
  846. }
  847. ls = newLState(opts[0])
  848. if !opts[0].SkipOpenLibs {
  849. ls.OpenLibs()
  850. }
  851. }
  852. return ls
  853. }
  854. func (ls *LState) Close() {
  855. atomic.AddInt32(&ls.stop, 1)
  856. for _, file := range ls.G.tempFiles {
  857. // ignore errors in these operations
  858. file.Close()
  859. os.Remove(file.Name())
  860. }
  861. }
  862. /* registry operations {{{ */
  863. func (ls *LState) GetTop() int {
  864. return ls.reg.Top() - ls.currentLocalBase()
  865. }
  866. func (ls *LState) SetTop(idx int) {
  867. base := ls.currentLocalBase()
  868. newtop := ls.indexToReg(idx) + 1
  869. if newtop < base {
  870. ls.reg.SetTop(base)
  871. } else {
  872. ls.reg.SetTop(newtop)
  873. }
  874. }
  875. func (ls *LState) Replace(idx int, value LValue) {
  876. base := ls.currentLocalBase()
  877. if idx > 0 {
  878. reg := base + idx - 1
  879. if reg < ls.reg.Top() {
  880. ls.reg.Set(reg, value)
  881. }
  882. } else if idx == 0 {
  883. } else if idx > RegistryIndex {
  884. if tidx := ls.reg.Top() + idx; tidx >= base {
  885. ls.reg.Set(tidx, value)
  886. }
  887. } else {
  888. switch idx {
  889. case RegistryIndex:
  890. if tb, ok := value.(*LTable); ok {
  891. ls.G.Registry = tb
  892. } else {
  893. ls.RaiseError("registry must be a table(%v)", value.Type().String())
  894. }
  895. case EnvironIndex:
  896. if ls.currentFrame == nil {
  897. ls.RaiseError("no calling environment")
  898. }
  899. if tb, ok := value.(*LTable); ok {
  900. ls.currentFrame.Fn.Env = tb
  901. } else {
  902. ls.RaiseError("environment must be a table(%v)", value.Type().String())
  903. }
  904. case GlobalsIndex:
  905. if tb, ok := value.(*LTable); ok {
  906. ls.G.Global = tb
  907. } else {
  908. ls.RaiseError("_G must be a table(%v)", value.Type().String())
  909. }
  910. default:
  911. fn := ls.currentFrame.Fn
  912. index := GlobalsIndex - idx - 1
  913. if index < len(fn.Upvalues) {
  914. fn.Upvalues[index].SetValue(value)
  915. }
  916. }
  917. }
  918. }
  919. func (ls *LState) Get(idx int) LValue {
  920. base := ls.currentLocalBase()
  921. if idx > 0 {
  922. reg := base + idx - 1
  923. if reg < ls.reg.Top() {
  924. return ls.reg.Get(reg)
  925. }
  926. return LNil
  927. } else if idx == 0 {
  928. return LNil
  929. } else if idx > RegistryIndex {
  930. tidx := ls.reg.Top() + idx
  931. if tidx < base {
  932. return LNil
  933. }
  934. return ls.reg.Get(tidx)
  935. } else {
  936. switch idx {
  937. case RegistryIndex:
  938. return ls.G.Registry
  939. case EnvironIndex:
  940. if ls.currentFrame == nil {
  941. return ls.Env
  942. }
  943. return ls.currentFrame.Fn.Env
  944. case GlobalsIndex:
  945. return ls.G.Global
  946. default:
  947. fn := ls.currentFrame.Fn
  948. index := GlobalsIndex - idx - 1
  949. if index < len(fn.Upvalues) {
  950. return fn.Upvalues[index].Value()
  951. }
  952. return LNil
  953. }
  954. }
  955. return LNil
  956. }
  957. func (ls *LState) Push(value LValue) {
  958. ls.reg.Push(value)
  959. }
  960. func (ls *LState) Pop(n int) {
  961. for i := 0; i < n; i++ {
  962. if ls.GetTop() == 0 {
  963. ls.RaiseError("register underflow")
  964. }
  965. ls.reg.Pop()
  966. }
  967. }
  968. func (ls *LState) Insert(value LValue, index int) {
  969. reg := ls.indexToReg(index)
  970. top := ls.reg.Top()
  971. if reg >= top {
  972. ls.reg.Set(reg, value)
  973. return
  974. }
  975. if reg <= ls.currentLocalBase() {
  976. reg = ls.currentLocalBase()
  977. }
  978. top--
  979. for ; top >= reg; top-- {
  980. ls.reg.Set(top+1, ls.reg.Get(top))
  981. }
  982. ls.reg.Set(reg, value)
  983. }
  984. func (ls *LState) Remove(index int) {
  985. reg := ls.indexToReg(index)
  986. top := ls.reg.Top()
  987. switch {
  988. case reg >= top:
  989. return
  990. case reg < ls.currentLocalBase():
  991. return
  992. case reg == top-1:
  993. ls.Pop(1)
  994. return
  995. }
  996. for i := reg; i < top-1; i++ {
  997. ls.reg.Set(i, ls.reg.Get(i+1))
  998. }
  999. ls.reg.SetTop(top - 1)
  1000. }
  1001. /* }}} */
  1002. /* object allocation {{{ */
  1003. func (ls *LState) NewTable() *LTable {
  1004. return newLTable(defaultArrayCap, defaultHashCap)
  1005. }
  1006. func (ls *LState) CreateTable(acap, hcap int) *LTable {
  1007. return newLTable(acap, hcap)
  1008. }
  1009. // NewThread returns a new LState that shares with the original state all global objects.
  1010. // If the original state has context.Context, the new state has a new child context of the original state and this function returns its cancel function.
  1011. func (ls *LState) NewThread() (*LState, context.CancelFunc) {
  1012. thread := newLState(ls.Options)
  1013. thread.G = ls.G
  1014. thread.Env = ls.Env
  1015. var f context.CancelFunc = nil
  1016. if ls.ctx != nil {
  1017. thread.mainLoop = mainLoopWithContext
  1018. thread.ctx, f = context.WithCancel(ls.ctx)
  1019. }
  1020. return thread, f
  1021. }
  1022. func (ls *LState) NewUserData() *LUserData {
  1023. return &LUserData{
  1024. Env: ls.currentEnv(),
  1025. Metatable: LNil,
  1026. }
  1027. }
  1028. func (ls *LState) NewFunction(fn LGFunction) *LFunction {
  1029. return newLFunctionG(fn, ls.currentEnv(), 0)
  1030. }
  1031. func (ls *LState) NewClosure(fn LGFunction, upvalues ...LValue) *LFunction {
  1032. cl := newLFunctionG(fn, ls.currentEnv(), len(upvalues))
  1033. for i, lv := range upvalues {
  1034. cl.Upvalues[i] = &Upvalue{}
  1035. cl.Upvalues[i].Close()
  1036. cl.Upvalues[i].SetValue(lv)
  1037. }
  1038. return cl
  1039. }
  1040. /* }}} */
  1041. /* toType {{{ */
  1042. func (ls *LState) ToBool(n int) bool {
  1043. return LVAsBool(ls.Get(n))
  1044. }
  1045. func (ls *LState) ToInt(n int) int {
  1046. if lv, ok := ls.Get(n).(LNumber); ok {
  1047. return int(lv)
  1048. }
  1049. if lv, ok := ls.Get(n).(LString); ok {
  1050. if num, err := parseNumber(string(lv)); err == nil {
  1051. return int(num)
  1052. }
  1053. }
  1054. return 0
  1055. }
  1056. func (ls *LState) ToInt64(n int) int64 {
  1057. if lv, ok := ls.Get(n).(LNumber); ok {
  1058. return int64(lv)
  1059. }
  1060. if lv, ok := ls.Get(n).(LString); ok {
  1061. if num, err := parseNumber(string(lv)); err == nil {
  1062. return int64(num)
  1063. }
  1064. }
  1065. return 0
  1066. }
  1067. func (ls *LState) ToNumber(n int) LNumber {
  1068. return LVAsNumber(ls.Get(n))
  1069. }
  1070. func (ls *LState) ToString(n int) string {
  1071. return LVAsString(ls.Get(n))
  1072. }
  1073. func (ls *LState) ToTable(n int) *LTable {
  1074. if lv, ok := ls.Get(n).(*LTable); ok {
  1075. return lv
  1076. }
  1077. return nil
  1078. }
  1079. func (ls *LState) ToFunction(n int) *LFunction {
  1080. if lv, ok := ls.Get(n).(*LFunction); ok {
  1081. return lv
  1082. }
  1083. return nil
  1084. }
  1085. func (ls *LState) ToUserData(n int) *LUserData {
  1086. if lv, ok := ls.Get(n).(*LUserData); ok {
  1087. return lv
  1088. }
  1089. return nil
  1090. }
  1091. func (ls *LState) ToThread(n int) *LState {
  1092. if lv, ok := ls.Get(n).(*LState); ok {
  1093. return lv
  1094. }
  1095. return nil
  1096. }
  1097. /* }}} */
  1098. /* error & debug operations {{{ */
  1099. // This function is equivalent to luaL_error( http://www.lua.org/manual/5.1/manual.html#luaL_error ).
  1100. func (ls *LState) RaiseError(format string, args ...interface{}) {
  1101. ls.raiseError(1, format, args...)
  1102. }
  1103. // This function is equivalent to lua_error( http://www.lua.org/manual/5.1/manual.html#lua_error ).
  1104. func (ls *LState) Error(lv LValue, level int) {
  1105. if str, ok := lv.(LString); ok {
  1106. ls.raiseError(level, string(str))
  1107. } else {
  1108. if !ls.hasErrorFunc {
  1109. ls.closeAllUpvalues()
  1110. }
  1111. ls.Push(lv)
  1112. ls.Panic(ls)
  1113. }
  1114. }
  1115. func (ls *LState) GetInfo(what string, dbg *Debug, fn LValue) (LValue, error) {
  1116. if !strings.HasPrefix(what, ">") {
  1117. fn = dbg.frame.Fn
  1118. } else {
  1119. what = what[1:]
  1120. }
  1121. f, ok := fn.(*LFunction)
  1122. if !ok {
  1123. return LNil, newApiErrorS(ApiErrorRun, "can not get debug info(an object in not a function)")
  1124. }
  1125. retfn := false
  1126. for _, c := range what {
  1127. switch c {
  1128. case 'f':
  1129. retfn = true
  1130. case 'S':
  1131. if dbg.frame != nil && dbg.frame.Parent == nil {
  1132. dbg.What = "main"
  1133. } else if f.IsG {
  1134. dbg.What = "G"
  1135. } else if dbg.frame != nil && dbg.frame.TailCall > 0 {
  1136. dbg.What = "tail"
  1137. } else {
  1138. dbg.What = "Lua"
  1139. }
  1140. if !f.IsG {
  1141. dbg.Source = f.Proto.SourceName
  1142. dbg.LineDefined = f.Proto.LineDefined
  1143. dbg.LastLineDefined = f.Proto.LastLineDefined
  1144. }
  1145. case 'l':
  1146. if !f.IsG && dbg.frame != nil {
  1147. if dbg.frame.Pc > 0 {
  1148. dbg.CurrentLine = f.Proto.DbgSourcePositions[dbg.frame.Pc-1]
  1149. }
  1150. } else {
  1151. dbg.CurrentLine = -1
  1152. }
  1153. case 'u':
  1154. dbg.NUpvalues = len(f.Upvalues)
  1155. case 'n':
  1156. if dbg.frame != nil {
  1157. dbg.Name = ls.rawFrameFuncName(dbg.frame)
  1158. }
  1159. default:
  1160. return LNil, newApiErrorS(ApiErrorRun, "invalid what: "+string(c))
  1161. }
  1162. }
  1163. if retfn {
  1164. return f, nil
  1165. }
  1166. return LNil, nil
  1167. }
  1168. func (ls *LState) GetStack(level int) (*Debug, bool) {
  1169. frame := ls.currentFrame
  1170. for ; level > 0 && frame != nil; frame = frame.Parent {
  1171. level--
  1172. if !frame.Fn.IsG {
  1173. level -= frame.TailCall
  1174. }
  1175. }
  1176. if level == 0 && frame != nil {
  1177. return &Debug{frame: frame}, true
  1178. } else if level < 0 && ls.stack.Sp() > 0 {
  1179. return &Debug{frame: ls.stack.At(0)}, true
  1180. }
  1181. return &Debug{}, false
  1182. }
  1183. func (ls *LState) GetLocal(dbg *Debug, no int) (string, LValue) {
  1184. frame := dbg.frame
  1185. if name := ls.findLocal(frame, no); len(name) > 0 {
  1186. return name, ls.reg.Get(frame.LocalBase + no - 1)
  1187. }
  1188. return "", LNil
  1189. }
  1190. func (ls *LState) SetLocal(dbg *Debug, no int, lv LValue) string {
  1191. frame := dbg.frame
  1192. if name := ls.findLocal(frame, no); len(name) > 0 {
  1193. ls.reg.Set(frame.LocalBase+no-1, lv)
  1194. return name
  1195. }
  1196. return ""
  1197. }
  1198. func (ls *LState) GetUpvalue(fn *LFunction, no int) (string, LValue) {
  1199. if fn.IsG {
  1200. return "", LNil
  1201. }
  1202. no--
  1203. if no >= 0 && no < len(fn.Upvalues) {
  1204. return fn.Proto.DbgUpvalues[no], fn.Upvalues[no].Value()
  1205. }
  1206. return "", LNil
  1207. }
  1208. func (ls *LState) SetUpvalue(fn *LFunction, no int, lv LValue) string {
  1209. if fn.IsG {
  1210. return ""
  1211. }
  1212. no--
  1213. if no >= 0 && no < len(fn.Upvalues) {
  1214. fn.Upvalues[no].SetValue(lv)
  1215. return fn.Proto.DbgUpvalues[no]
  1216. }
  1217. return ""
  1218. }
  1219. /* }}} */
  1220. /* env operations {{{ */
  1221. func (ls *LState) GetFEnv(obj LValue) LValue {
  1222. switch lv := obj.(type) {
  1223. case *LFunction:
  1224. return lv.Env
  1225. case *LUserData:
  1226. return lv.Env
  1227. case *LState:
  1228. return lv.Env
  1229. }
  1230. return LNil
  1231. }
  1232. func (ls *LState) SetFEnv(obj LValue, env LValue) {
  1233. tb, ok := env.(*LTable)
  1234. if !ok {
  1235. ls.RaiseError("cannot use %v as an environment", env.Type().String())
  1236. }
  1237. switch lv := obj.(type) {
  1238. case *LFunction:
  1239. lv.Env = tb
  1240. case *LUserData:
  1241. lv.Env = tb
  1242. case *LState:
  1243. lv.Env = tb
  1244. }
  1245. /* do nothing */
  1246. }
  1247. /* }}} */
  1248. /* table operations {{{ */
  1249. func (ls *LState) RawGet(tb *LTable, key LValue) LValue {
  1250. return tb.RawGet(key)
  1251. }
  1252. func (ls *LState) RawGetInt(tb *LTable, key int) LValue {
  1253. return tb.RawGetInt(key)
  1254. }
  1255. func (ls *LState) GetField(obj LValue, skey string) LValue {
  1256. return ls.getFieldString(obj, skey)
  1257. }
  1258. func (ls *LState) GetTable(obj LValue, key LValue) LValue {
  1259. return ls.getField(obj, key)
  1260. }
  1261. func (ls *LState) RawSet(tb *LTable, key LValue, value LValue) {
  1262. if n, ok := key.(LNumber); ok && math.IsNaN(float64(n)) {
  1263. ls.RaiseError("table index is NaN")
  1264. } else if key == LNil {
  1265. ls.RaiseError("table index is nil")
  1266. }
  1267. tb.RawSet(key, value)
  1268. }
  1269. func (ls *LState) RawSetInt(tb *LTable, key int, value LValue) {
  1270. tb.RawSetInt(key, value)
  1271. }
  1272. func (ls *LState) SetField(obj LValue, key string, value LValue) {
  1273. ls.setFieldString(obj, key, value)
  1274. }
  1275. func (ls *LState) SetTable(obj LValue, key LValue, value LValue) {
  1276. ls.setField(obj, key, value)
  1277. }
  1278. func (ls *LState) ForEach(tb *LTable, cb func(LValue, LValue)) {
  1279. tb.ForEach(cb)
  1280. }
  1281. func (ls *LState) GetGlobal(name string) LValue {
  1282. return ls.GetField(ls.Get(GlobalsIndex), name)
  1283. }
  1284. func (ls *LState) SetGlobal(name string, value LValue) {
  1285. ls.SetField(ls.Get(GlobalsIndex), name, value)
  1286. }
  1287. func (ls *LState) Next(tb *LTable, key LValue) (LValue, LValue) {
  1288. return tb.Next(key)
  1289. }
  1290. /* }}} */
  1291. /* unary operations {{{ */
  1292. func (ls *LState) ObjLen(v1 LValue) int {
  1293. if v1.Type() == LTString {
  1294. return len(string(v1.(LString)))
  1295. }
  1296. op := ls.metaOp1(v1, "__len")
  1297. if op.Type() == LTFunction {
  1298. ls.Push(op)
  1299. ls.Push(v1)
  1300. ls.Call(1, 1)
  1301. ret := ls.reg.Pop()
  1302. if ret.Type() == LTNumber {
  1303. return int(ret.(LNumber))
  1304. }
  1305. } else if v1.Type() == LTTable {
  1306. return v1.(*LTable).Len()
  1307. }
  1308. return 0
  1309. }
  1310. /* }}} */
  1311. /* binary operations {{{ */
  1312. func (ls *LState) Concat(values ...LValue) string {
  1313. top := ls.reg.Top()
  1314. for _, value := range values {
  1315. ls.reg.Push(value)
  1316. }
  1317. ret := stringConcat(ls, len(values), ls.reg.Top()-1)
  1318. ls.reg.SetTop(top)
  1319. return LVAsString(ret)
  1320. }
  1321. func (ls *LState) LessThan(lhs, rhs LValue) bool {
  1322. return lessThan(ls, lhs, rhs)
  1323. }
  1324. func (ls *LState) Equal(lhs, rhs LValue) bool {
  1325. return equals(ls, lhs, rhs, false)
  1326. }
  1327. func (ls *LState) RawEqual(lhs, rhs LValue) bool {
  1328. return equals(ls, lhs, rhs, true)
  1329. }
  1330. /* }}} */
  1331. /* register operations {{{ */
  1332. func (ls *LState) Register(name string, fn LGFunction) {
  1333. ls.SetGlobal(name, ls.NewFunction(fn))
  1334. }
  1335. /* }}} */
  1336. /* load and function call operations {{{ */
  1337. func container2proto(container *functionProtoContainer) *FunctionProto {
  1338. protos := []*FunctionProto{}
  1339. for _, c := range container.FunctionPrototypes {
  1340. protos = append(protos, container2proto(c))
  1341. }
  1342. constants := []LValue{}
  1343. stringConstants := []string{}
  1344. for _, c := range container.Constants {
  1345. if s, ok := c.(string); ok {
  1346. constants = append(constants, LString(s))
  1347. stringConstants = append(stringConstants, s)
  1348. } else {
  1349. constants = append(constants, LNumber(c.(float64)))
  1350. }
  1351. }
  1352. return &FunctionProto{
  1353. SourceName: container.SourceName,
  1354. LineDefined: container.LineDefined,
  1355. LastLineDefined: container.LastLineDefined,
  1356. NumUpvalues: container.NumUpvalues,
  1357. NumParameters: container.NumParameters,
  1358. IsVarArg: container.IsVarArg,
  1359. NumUsedRegisters: container.NumUsedRegisters,
  1360. Code: container.Code,
  1361. Constants: constants,
  1362. FunctionPrototypes: protos,
  1363. DbgSourcePositions: container.DbgSourcePositions,
  1364. DbgLocals: container.DbgLocals,
  1365. DbgCalls: container.DbgCalls,
  1366. DbgUpvalues: container.DbgUpvalues,
  1367. stringConstants: stringConstants,
  1368. }
  1369. }
  1370. func (ls *LState) Load(reader io.Reader, name string) (*LFunction, error) {
  1371. b := bufio.NewReader(reader)
  1372. if sbuf, err := b.Peek(4); err == nil {
  1373. if string(sbuf) == dumpSignature {
  1374. b.Discard(4)
  1375. buf, err := ioutil.ReadAll(b)
  1376. if err != nil {
  1377. ls.RaiseError(err.Error())
  1378. }
  1379. var container functionProtoContainer
  1380. if err := msgpack.Unmarshal(buf, &container); err != nil {
  1381. ls.RaiseError(err.Error())
  1382. }
  1383. return newLFunctionL(container2proto(&container), ls.currentEnv(), 0), nil
  1384. }
  1385. }
  1386. chunk, err := parse.Parse(b, name)
  1387. if err != nil {
  1388. return nil, newApiErrorE(ApiErrorSyntax, err)
  1389. }
  1390. proto, err := Compile(chunk, name)
  1391. if err != nil {
  1392. return nil, newApiErrorE(ApiErrorSyntax, err)
  1393. }
  1394. return newLFunctionL(proto, ls.currentEnv(), 0), nil
  1395. }
  1396. func (ls *LState) Call(nargs, nret int) {
  1397. ls.callR(nargs, nret, -1)
  1398. }
  1399. func (ls *LState) PCall(nargs, nret int, errfunc *LFunction) (err error) {
  1400. err = nil
  1401. sp := ls.stack.Sp()
  1402. base := ls.reg.Top() - nargs - 1
  1403. oldpanic := ls.Panic
  1404. ls.Panic = panicWithoutTraceback
  1405. if errfunc != nil {
  1406. ls.hasErrorFunc = true
  1407. }
  1408. defer func() {
  1409. ls.Panic = oldpanic
  1410. ls.hasErrorFunc = false
  1411. rcv := recover()
  1412. if rcv != nil {
  1413. if _, ok := rcv.(*ApiError); !ok {
  1414. err = newApiErrorS(ApiErrorPanic, fmt.Sprint(rcv))
  1415. if ls.Options.IncludeGoStackTrace {
  1416. buf := make([]byte, 4096)
  1417. runtime.Stack(buf, false)
  1418. err.(*ApiError).StackTrace = strings.Trim(string(buf), "\000") + "\n" + ls.stackTrace(0)
  1419. }
  1420. } else {
  1421. err = rcv.(*ApiError)
  1422. }
  1423. if errfunc != nil {
  1424. ls.Push(errfunc)
  1425. ls.Push(err.(*ApiError).Object)
  1426. ls.Panic = panicWithoutTraceback
  1427. defer func() {
  1428. ls.Panic = oldpanic
  1429. rcv := recover()
  1430. if rcv != nil {
  1431. if _, ok := rcv.(*ApiError); !ok {
  1432. err = newApiErrorS(ApiErrorPanic, fmt.Sprint(rcv))
  1433. if ls.Options.IncludeGoStackTrace {
  1434. buf := make([]byte, 4096)
  1435. runtime.Stack(buf, false)
  1436. err.(*ApiError).StackTrace = strings.Trim(string(buf), "\000") + ls.stackTrace(0)
  1437. }
  1438. } else {
  1439. err = rcv.(*ApiError)
  1440. err.(*ApiError).StackTrace = ls.stackTrace(0)
  1441. }
  1442. }
  1443. }()
  1444. ls.Call(1, 1)
  1445. err = newApiError(ApiErrorError, ls.Get(-1))
  1446. } else if len(err.(*ApiError).StackTrace) == 0 {
  1447. err.(*ApiError).StackTrace = ls.stackTrace(0)
  1448. }
  1449. ls.reg.SetTop(base)
  1450. }
  1451. ls.stack.SetSp(sp)
  1452. if sp == 0 {
  1453. ls.currentFrame = nil
  1454. }
  1455. }()
  1456. ls.Call(nargs, nret)
  1457. return
  1458. }
  1459. func (ls *LState) GPCall(fn LGFunction, data LValue) error {
  1460. ls.Push(newLFunctionG(fn, ls.currentEnv(), 0))
  1461. ls.Push(data)
  1462. return ls.PCall(1, MultRet, nil)
  1463. }
  1464. func (ls *LState) CallByParam(cp P, args ...LValue) error {
  1465. ls.Push(cp.Fn)
  1466. for _, arg := range args {
  1467. ls.Push(arg)
  1468. }
  1469. if cp.Protect {
  1470. return ls.PCall(len(args), cp.NRet, cp.Handler)
  1471. }
  1472. ls.Call(len(args), cp.NRet)
  1473. return nil
  1474. }
  1475. /* }}} */
  1476. /* metatable operations {{{ */
  1477. func (ls *LState) GetMetatable(obj LValue) LValue {
  1478. return ls.metatable(obj, false)
  1479. }
  1480. func (ls *LState) SetMetatable(obj LValue, mt LValue) {
  1481. switch mt.(type) {
  1482. case *LNilType, *LTable:
  1483. default:
  1484. ls.RaiseError("metatable must be a table or nil, but got %v", mt.Type().String())
  1485. }
  1486. switch v := obj.(type) {
  1487. case *LTable:
  1488. v.Metatable = mt
  1489. case *LUserData:
  1490. v.Metatable = mt
  1491. default:
  1492. ls.G.builtinMts[int(obj.Type())] = mt
  1493. }
  1494. }
  1495. /* }}} */
  1496. /* coroutine operations {{{ */
  1497. func (ls *LState) Status(th *LState) string {
  1498. status := "suspended"
  1499. if th.Dead {
  1500. status = "dead"
  1501. } else if ls.G.CurrentThread == th {
  1502. status = "running"
  1503. } else if ls.Parent == th {
  1504. status = "normal"
  1505. }
  1506. return status
  1507. }
  1508. func (ls *LState) Resume(th *LState, fn *LFunction, args ...LValue) (ResumeState, error, []LValue) {
  1509. isstarted := th.isStarted()
  1510. if !isstarted {
  1511. base := 0
  1512. th.stack.Push(callFrame{
  1513. Fn: fn,
  1514. Pc: 0,
  1515. Base: base,
  1516. LocalBase: base + 1,
  1517. ReturnBase: base,
  1518. NArgs: 0,
  1519. NRet: MultRet,
  1520. Parent: nil,
  1521. TailCall: 0,
  1522. })
  1523. }
  1524. if ls.G.CurrentThread == th {
  1525. return ResumeError, newApiErrorS(ApiErrorRun, "can not resume a running thread"), nil
  1526. }
  1527. if th.Dead {
  1528. return ResumeError, newApiErrorS(ApiErrorRun, "can not resume a dead thread"), nil
  1529. }
  1530. th.Parent = ls
  1531. ls.G.CurrentThread = th
  1532. if !isstarted {
  1533. cf := th.stack.Last()
  1534. th.currentFrame = cf
  1535. th.SetTop(0)
  1536. for _, arg := range args {
  1537. th.Push(arg)
  1538. }
  1539. cf.NArgs = len(args)
  1540. th.initCallFrame(cf)
  1541. th.Panic = panicWithoutTraceback
  1542. } else {
  1543. for _, arg := range args {
  1544. th.Push(arg)
  1545. }
  1546. }
  1547. top := ls.GetTop()
  1548. threadRun(th)
  1549. haserror := LVIsFalse(ls.Get(top + 1))
  1550. ret := make([]LValue, 0, ls.GetTop())
  1551. for idx := top + 2; idx <= ls.GetTop(); idx++ {
  1552. ret = append(ret, ls.Get(idx))
  1553. }
  1554. if len(ret) == 0 {
  1555. ret = append(ret, LNil)
  1556. }
  1557. ls.SetTop(top)
  1558. if haserror {
  1559. return ResumeError, newApiError(ApiErrorRun, ret[0]), nil
  1560. } else if th.stack.IsEmpty() {
  1561. return ResumeOK, nil, ret
  1562. }
  1563. return ResumeYield, nil, ret
  1564. }
  1565. func (ls *LState) Yield(values ...LValue) int {
  1566. ls.SetTop(0)
  1567. for _, lv := range values {
  1568. ls.Push(lv)
  1569. }
  1570. return -1
  1571. }
  1572. func (ls *LState) XMoveTo(other *LState, n int) {
  1573. if ls == other {
  1574. return
  1575. }
  1576. top := ls.GetTop()
  1577. n = intMin(n, top)
  1578. for i := n; i > 0; i-- {
  1579. other.Push(ls.Get(top - i + 1))
  1580. }
  1581. ls.SetTop(top - n)
  1582. }
  1583. /* }}} */
  1584. /* GopherLua original APIs {{{ */
  1585. // Set maximum memory size. This function can only be called from the main thread.
  1586. func (ls *LState) SetMx(mx int) {
  1587. if ls.Parent != nil {
  1588. ls.RaiseError("sub threads are not allowed to set a memory limit")
  1589. }
  1590. go func() {
  1591. limit := uint64(mx * 1024 * 1024) //MB
  1592. var s runtime.MemStats
  1593. for ls.stop == 0 {
  1594. runtime.ReadMemStats(&s)
  1595. if s.Alloc >= limit {
  1596. fmt.Println("out of memory")
  1597. os.Exit(3)
  1598. }
  1599. time.Sleep(100 * time.Millisecond)
  1600. }
  1601. }()
  1602. }
  1603. // SetContext set a context ctx to this LState. The provided ctx must be non-nil.
  1604. func (ls *LState) SetContext(ctx context.Context) {
  1605. ls.mainLoop = mainLoopWithContext
  1606. ls.ctx = ctx
  1607. }
  1608. // Context returns the LState's context. To change the context, use WithContext.
  1609. func (ls *LState) Context() context.Context {
  1610. return ls.ctx
  1611. }
  1612. // RemoveContext removes the context associated with this LState and returns this context.
  1613. func (ls *LState) RemoveContext() context.Context {
  1614. oldctx := ls.ctx
  1615. ls.mainLoop = mainLoop
  1616. ls.ctx = nil
  1617. return oldctx
  1618. }
  1619. // Converts the Lua value at the given acceptable index to the chan LValue.
  1620. func (ls *LState) ToChannel(n int) chan LValue {
  1621. if lv, ok := ls.Get(n).(LChannel); ok {
  1622. return (chan LValue)(lv)
  1623. }
  1624. return nil
  1625. }
  1626. /* }}} */
  1627. /* }}} */
  1628. //