_state.go 47 KB

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