README.rst 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. ===============================================================================
  2. GopherLua: VM and compiler for Lua in Go.
  3. ===============================================================================
  4. .. image:: https://pkg.go.dev/badge/github.com/yuin/gopher-lua.svg
  5. :target: https://pkg.go.dev/github.com/yuin/gopher-lua
  6. .. image:: https://github.com/yuin/gopher-lua/workflows/test/badge.svg?branch=master&event=push
  7. :target: https://github.com/yuin/gopher-lua/actions?query=workflow:test
  8. .. image:: https://coveralls.io/repos/github/yuin/gopher-lua/badge.svg?branch=master
  9. :target: https://coveralls.io/github/yuin/gopher-lua
  10. .. image:: https://badges.gitter.im/Join%20Chat.svg
  11. :alt: Join the chat at https://gitter.im/yuin/gopher-lua
  12. :target: https://gitter.im/yuin/gopher-lua?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
  13. |
  14. GopherLua is a Lua5.1(+ `goto` statement in Lua5.2) VM and compiler written in Go. GopherLua has a same goal
  15. with Lua: **Be a scripting language with extensible semantics** . It provides
  16. Go APIs that allow you to easily embed a scripting language to your Go host
  17. programs.
  18. .. contents::
  19. :depth: 1
  20. ----------------------------------------------------------------
  21. Design principle
  22. ----------------------------------------------------------------
  23. - Be a scripting language with extensible semantics.
  24. - User-friendly Go API
  25. - The stack based API like the one used in the original Lua
  26. implementation will cause a performance improvements in GopherLua
  27. (It will reduce memory allocations and concrete type <-> interface conversions).
  28. GopherLua API is **not** the stack based API.
  29. GopherLua give preference to the user-friendliness over the performance.
  30. ----------------------------------------------------------------
  31. How about performance?
  32. ----------------------------------------------------------------
  33. GopherLua is not fast but not too slow, I think.
  34. GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.
  35. There are some benchmarks on the `wiki page <https://github.com/yuin/gopher-lua/wiki/Benchmarks>`_ .
  36. ----------------------------------------------------------------
  37. Installation
  38. ----------------------------------------------------------------
  39. .. code-block:: bash
  40. go get github.com/yuin/gopher-lua
  41. GopherLua supports >= Go1.9.
  42. ----------------------------------------------------------------
  43. Usage
  44. ----------------------------------------------------------------
  45. GopherLua APIs perform in much the same way as Lua, **but the stack is used only
  46. for passing arguments and receiving returned values.**
  47. GopherLua supports channel operations. See **"Goroutines"** section.
  48. Import a package.
  49. .. code-block:: go
  50. import (
  51. "github.com/yuin/gopher-lua"
  52. )
  53. Run scripts in the VM.
  54. .. code-block:: go
  55. L := lua.NewState()
  56. defer L.Close()
  57. if err := L.DoString(`print("hello")`); err != nil {
  58. panic(err)
  59. }
  60. .. code-block:: go
  61. L := lua.NewState()
  62. defer L.Close()
  63. if err := L.DoFile("hello.lua"); err != nil {
  64. panic(err)
  65. }
  66. Refer to `Lua Reference Manual <http://www.lua.org/manual/5.1/>`_ and `Go doc <http://godoc.org/github.com/yuin/gopher-lua>`_ for further information.
  67. Note that elements that are not commented in `Go doc <http://godoc.org/github.com/yuin/gopher-lua>`_ equivalent to `Lua Reference Manual <http://www.lua.org/manual/5.1/>`_ , except GopherLua uses objects instead of Lua stack indices.
  68. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69. Data model
  70. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  71. All data in a GopherLua program is an ``LValue`` . ``LValue`` is an interface
  72. type that has following methods.
  73. - ``String() string``
  74. - ``Type() LValueType``
  75. Objects implement an LValue interface are
  76. ================ ========================= ================== =======================
  77. Type name Go type Type() value Constants
  78. ================ ========================= ================== =======================
  79. ``LNilType`` (constants) ``LTNil`` ``LNil``
  80. ``LBool`` (constants) ``LTBool`` ``LTrue``, ``LFalse``
  81. ``LNumber`` float64 ``LTNumber`` ``-``
  82. ``LString`` string ``LTString`` ``-``
  83. ``LFunction`` struct pointer ``LTFunction`` ``-``
  84. ``LUserData`` struct pointer ``LTUserData`` ``-``
  85. ``LState`` struct pointer ``LTThread`` ``-``
  86. ``LTable`` struct pointer ``LTTable`` ``-``
  87. ``LChannel`` chan LValue ``LTChannel`` ``-``
  88. ================ ========================= ================== =======================
  89. You can test an object type in Go way(type assertion) or using a ``Type()`` value.
  90. .. code-block:: go
  91. lv := L.Get(-1) // get the value at the top of the stack
  92. if str, ok := lv.(lua.LString); ok {
  93. // lv is LString
  94. fmt.Println(string(str))
  95. }
  96. if lv.Type() != lua.LTString {
  97. panic("string required.")
  98. }
  99. .. code-block:: go
  100. lv := L.Get(-1) // get the value at the top of the stack
  101. if tbl, ok := lv.(*lua.LTable); ok {
  102. // lv is LTable
  103. fmt.Println(L.ObjLen(tbl))
  104. }
  105. Note that ``LBool`` , ``LNumber`` , ``LString`` is not a pointer.
  106. To test ``LNilType`` and ``LBool``, You **must** use pre-defined constants.
  107. .. code-block:: go
  108. lv := L.Get(-1) // get the value at the top of the stack
  109. if lv == lua.LTrue { // correct
  110. }
  111. if bl, ok := lv.(lua.LBool); ok && bool(bl) { // wrong
  112. }
  113. In Lua, both ``nil`` and ``false`` make a condition false. ``LVIsFalse`` and ``LVAsBool`` implement this specification.
  114. .. code-block:: go
  115. lv := L.Get(-1) // get the value at the top of the stack
  116. if lua.LVIsFalse(lv) { // lv is nil or false
  117. }
  118. if lua.LVAsBool(lv) { // lv is neither nil nor false
  119. }
  120. Objects that based on go structs(``LFunction``. ``LUserData``, ``LTable``)
  121. have some public methods and fields. You can use these methods and fields for
  122. performance and debugging, but there are some limitations.
  123. - Metatable does not work.
  124. - No error handlings.
  125. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  126. Callstack & Registry size
  127. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  128. The size of an ``LState``'s callstack controls the maximum call depth for Lua functions within a script (Go function calls do not count).
  129. The registry of an ``LState`` implements stack storage for calling functions (both Lua and Go functions) and also for temporary variables in expressions. Its storage requirements will increase with callstack usage and also with code complexity.
  130. Both the registry and the callstack can be set to either a fixed size or to auto size.
  131. When you have a large number of ``LStates`` instantiated in a process, it's worth taking the time to tune the registry and callstack options.
  132. +++++++++
  133. Registry
  134. +++++++++
  135. The registry can have an initial size, a maximum size and a step size configured on a per ``LState`` basis. This will allow the registry to grow as needed. It will not shrink again after growing.
  136. .. code-block:: go
  137. L := lua.NewState(lua.Options{
  138. RegistrySize: 1024 * 20, // this is the initial size of the registry
  139. RegistryMaxSize: 1024 * 80, // this is the maximum size that the registry can grow to. If set to `0` (the default) then the registry will not auto grow
  140. RegistryGrowStep: 32, // this is how much to step up the registry by each time it runs out of space. The default is `32`.
  141. })
  142. defer L.Close()
  143. A registry which is too small for a given script will ultimately result in a panic. A registry which is too big will waste memory (which can be significant if many ``LStates`` are instantiated).
  144. Auto growing registries incur a small performance hit at the point they are resized but will not otherwise affect performance.
  145. +++++++++
  146. Callstack
  147. +++++++++
  148. The callstack can operate in two different modes, fixed or auto size.
  149. A fixed size callstack has the highest performance and has a fixed memory overhead.
  150. An auto sizing callstack will allocate and release callstack pages on demand which will ensure the minimum amount of memory is in use at any time. The downside is it will incur a small performance impact every time a new page of callframes is allocated.
  151. By default an ``LState`` will allocate and free callstack frames in pages of 8, so the allocation overhead is not incurred on every function call. It is very likely that the performance impact of an auto resizing callstack will be negligible for most use cases.
  152. .. code-block:: go
  153. L := lua.NewState(lua.Options{
  154. CallStackSize: 120, // this is the maximum callstack size of this LState
  155. MinimizeStackMemory: true, // Defaults to `false` if not specified. If set, the callstack will auto grow and shrink as needed up to a max of `CallStackSize`. If not set, the callstack will be fixed at `CallStackSize`.
  156. })
  157. defer L.Close()
  158. ++++++++++++++++
  159. Option defaults
  160. ++++++++++++++++
  161. The above examples show how to customize the callstack and registry size on a per ``LState`` basis. You can also adjust some defaults for when options are not specified by altering the values of ``lua.RegistrySize``, ``lua.RegistryGrowStep`` and ``lua.CallStackSize``.
  162. An ``LState`` object that has been created by ``*LState#NewThread()`` inherits the callstack & registry size from the parent ``LState`` object.
  163. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  164. Miscellaneous lua.NewState options
  165. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  166. - **Options.SkipOpenLibs bool(default false)**
  167. - By default, GopherLua opens all built-in libraries when new LState is created.
  168. - You can skip this behaviour by setting this to ``true`` .
  169. - Using the various `OpenXXX(L *LState) int` functions you can open only those libraries that you require, for an example see below.
  170. - **Options.IncludeGoStackTrace bool(default false)**
  171. - By default, GopherLua does not show Go stack traces when panics occur.
  172. - You can get Go stack traces by setting this to ``true`` .
  173. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  174. API
  175. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  176. Refer to `Lua Reference Manual <http://www.lua.org/manual/5.1/>`_ and `Go doc(LState methods) <http://godoc.org/github.com/yuin/gopher-lua>`_ for further information.
  177. +++++++++++++++++++++++++++++++++++++++++
  178. Calling Go from Lua
  179. +++++++++++++++++++++++++++++++++++++++++
  180. .. code-block:: go
  181. func Double(L *lua.LState) int {
  182. lv := L.ToInt(1) /* get argument */
  183. L.Push(lua.LNumber(lv * 2)) /* push result */
  184. return 1 /* number of results */
  185. }
  186. func main() {
  187. L := lua.NewState()
  188. defer L.Close()
  189. L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
  190. }
  191. .. code-block:: lua
  192. print(double(20)) -- > "40"
  193. Any function registered with GopherLua is a ``lua.LGFunction``, defined in ``value.go``
  194. .. code-block:: go
  195. type LGFunction func(*LState) int
  196. Working with coroutines.
  197. .. code-block:: go
  198. co, _ := L.NewThread() /* create a new thread */
  199. fn := L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */
  200. for {
  201. st, err, values := L.Resume(co, fn)
  202. if st == lua.ResumeError {
  203. fmt.Println("yield break(error)")
  204. fmt.Println(err.Error())
  205. break
  206. }
  207. for i, lv := range values {
  208. fmt.Printf("%v : %v\n", i, lv)
  209. }
  210. if st == lua.ResumeOK {
  211. fmt.Println("yield break(ok)")
  212. break
  213. }
  214. }
  215. +++++++++++++++++++++++++++++++++++++++++
  216. Opening a subset of builtin modules
  217. +++++++++++++++++++++++++++++++++++++++++
  218. The following demonstrates how to open a subset of the built-in modules in Lua, say for example to avoid enabling modules with access to local files or system calls.
  219. main.go
  220. .. code-block:: go
  221. func main() {
  222. L := lua.NewState(lua.Options{SkipOpenLibs: true})
  223. defer L.Close()
  224. for _, pair := range []struct {
  225. n string
  226. f lua.LGFunction
  227. }{
  228. {lua.LoadLibName, lua.OpenPackage}, // Must be first
  229. {lua.BaseLibName, lua.OpenBase},
  230. {lua.TabLibName, lua.OpenTable},
  231. } {
  232. if err := L.CallByParam(lua.P{
  233. Fn: L.NewFunction(pair.f),
  234. NRet: 0,
  235. Protect: true,
  236. }, lua.LString(pair.n)); err != nil {
  237. panic(err)
  238. }
  239. }
  240. if err := L.DoFile("main.lua"); err != nil {
  241. panic(err)
  242. }
  243. }
  244. +++++++++++++++++++++++++++++++++++++++++
  245. Creating a module by Go
  246. +++++++++++++++++++++++++++++++++++++++++
  247. mymodule.go
  248. .. code-block:: go
  249. package mymodule
  250. import (
  251. "github.com/yuin/gopher-lua"
  252. )
  253. func Loader(L *lua.LState) int {
  254. // register functions to the table
  255. mod := L.SetFuncs(L.NewTable(), exports)
  256. // register other stuff
  257. L.SetField(mod, "name", lua.LString("value"))
  258. // returns the module
  259. L.Push(mod)
  260. return 1
  261. }
  262. var exports = map[string]lua.LGFunction{
  263. "myfunc": myfunc,
  264. }
  265. func myfunc(L *lua.LState) int {
  266. return 0
  267. }
  268. mymain.go
  269. .. code-block:: go
  270. package main
  271. import (
  272. "./mymodule"
  273. "github.com/yuin/gopher-lua"
  274. )
  275. func main() {
  276. L := lua.NewState()
  277. defer L.Close()
  278. L.PreloadModule("mymodule", mymodule.Loader)
  279. if err := L.DoFile("main.lua"); err != nil {
  280. panic(err)
  281. }
  282. }
  283. main.lua
  284. .. code-block:: lua
  285. local m = require("mymodule")
  286. m.myfunc()
  287. print(m.name)
  288. +++++++++++++++++++++++++++++++++++++++++
  289. Calling Lua from Go
  290. +++++++++++++++++++++++++++++++++++++++++
  291. .. code-block:: go
  292. L := lua.NewState()
  293. defer L.Close()
  294. if err := L.DoFile("double.lua"); err != nil {
  295. panic(err)
  296. }
  297. if err := L.CallByParam(lua.P{
  298. Fn: L.GetGlobal("double"),
  299. NRet: 1,
  300. Protect: true,
  301. }, lua.LNumber(10)); err != nil {
  302. panic(err)
  303. }
  304. ret := L.Get(-1) // returned value
  305. L.Pop(1) // remove received value
  306. If ``Protect`` is false, GopherLua will panic instead of returning an ``error`` value.
  307. +++++++++++++++++++++++++++++++++++++++++
  308. User-Defined types
  309. +++++++++++++++++++++++++++++++++++++++++
  310. You can extend GopherLua with new types written in Go.
  311. ``LUserData`` is provided for this purpose.
  312. .. code-block:: go
  313. type Person struct {
  314. Name string
  315. }
  316. const luaPersonTypeName = "person"
  317. // Registers my person type to given L.
  318. func registerPersonType(L *lua.LState) {
  319. mt := L.NewTypeMetatable(luaPersonTypeName)
  320. L.SetGlobal("person", mt)
  321. // static attributes
  322. L.SetField(mt, "new", L.NewFunction(newPerson))
  323. // methods
  324. L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
  325. }
  326. // Constructor
  327. func newPerson(L *lua.LState) int {
  328. person := &Person{L.CheckString(1)}
  329. ud := L.NewUserData()
  330. ud.Value = person
  331. L.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
  332. L.Push(ud)
  333. return 1
  334. }
  335. // Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.
  336. func checkPerson(L *lua.LState) *Person {
  337. ud := L.CheckUserData(1)
  338. if v, ok := ud.Value.(*Person); ok {
  339. return v
  340. }
  341. L.ArgError(1, "person expected")
  342. return nil
  343. }
  344. var personMethods = map[string]lua.LGFunction{
  345. "name": personGetSetName,
  346. }
  347. // Getter and setter for the Person#Name
  348. func personGetSetName(L *lua.LState) int {
  349. p := checkPerson(L)
  350. if L.GetTop() == 2 {
  351. p.Name = L.CheckString(2)
  352. return 0
  353. }
  354. L.Push(lua.LString(p.Name))
  355. return 1
  356. }
  357. func main() {
  358. L := lua.NewState()
  359. defer L.Close()
  360. registerPersonType(L)
  361. if err := L.DoString(`
  362. p = person.new("Steeve")
  363. print(p:name()) -- "Steeve"
  364. p:name("Alice")
  365. print(p:name()) -- "Alice"
  366. `); err != nil {
  367. panic(err)
  368. }
  369. }
  370. +++++++++++++++++++++++++++++++++++++++++
  371. Terminating a running LState
  372. +++++++++++++++++++++++++++++++++++++++++
  373. GopherLua supports the `Go Concurrency Patterns: Context <https://blog.golang.org/context>`_ .
  374. .. code-block:: go
  375. L := lua.NewState()
  376. defer L.Close()
  377. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  378. defer cancel()
  379. // set the context to our LState
  380. L.SetContext(ctx)
  381. err := L.DoString(`
  382. local clock = os.clock
  383. function sleep(n) -- seconds
  384. local t0 = clock()
  385. while clock() - t0 <= n do end
  386. end
  387. sleep(3)
  388. `)
  389. // err.Error() contains "context deadline exceeded"
  390. With coroutines
  391. .. code-block:: go
  392. L := lua.NewState()
  393. defer L.Close()
  394. ctx, cancel := context.WithCancel(context.Background())
  395. L.SetContext(ctx)
  396. defer cancel()
  397. L.DoString(`
  398. function coro()
  399. local i = 0
  400. while true do
  401. coroutine.yield(i)
  402. i = i+1
  403. end
  404. return i
  405. end
  406. `)
  407. co, cocancel := L.NewThread()
  408. defer cocancel()
  409. fn := L.GetGlobal("coro").(*LFunction)
  410. _, err, values := L.Resume(co, fn) // err is nil
  411. cancel() // cancel the parent context
  412. _, err, values = L.Resume(co, fn) // err is NOT nil : child context was canceled
  413. **Note that using a context causes performance degradation.**
  414. .. code-block::
  415. time ./glua-with-context.exe fib.lua
  416. 9227465
  417. 0.01s user 0.11s system 1% cpu 7.505 total
  418. time ./glua-without-context.exe fib.lua
  419. 9227465
  420. 0.01s user 0.01s system 0% cpu 5.306 total
  421. +++++++++++++++++++++++++++++++++++++++++
  422. Sharing Lua byte code between LStates
  423. +++++++++++++++++++++++++++++++++++++++++
  424. Calling ``DoFile`` will load a Lua script, compile it to byte code and run the byte code in a ``LState``.
  425. If you have multiple ``LStates`` which are all required to run the same script, you can share the byte code between them,
  426. which will save on memory.
  427. Sharing byte code is safe as it is read only and cannot be altered by lua scripts.
  428. .. code-block:: go
  429. // CompileLua reads the passed lua file from disk and compiles it.
  430. func CompileLua(filePath string) (*lua.FunctionProto, error) {
  431. file, err := os.Open(filePath)
  432. defer file.Close()
  433. if err != nil {
  434. return nil, err
  435. }
  436. reader := bufio.NewReader(file)
  437. chunk, err := parse.Parse(reader, filePath)
  438. if err != nil {
  439. return nil, err
  440. }
  441. proto, err := lua.Compile(chunk, filePath)
  442. if err != nil {
  443. return nil, err
  444. }
  445. return proto, nil
  446. }
  447. // DoCompiledFile takes a FunctionProto, as returned by CompileLua, and runs it in the LState. It is equivalent
  448. // to calling DoFile on the LState with the original source file.
  449. func DoCompiledFile(L *lua.LState, proto *lua.FunctionProto) error {
  450. lfunc := L.NewFunctionFromProto(proto)
  451. L.Push(lfunc)
  452. return L.PCall(0, lua.MultRet, nil)
  453. }
  454. // Example shows how to share the compiled byte code from a lua script between multiple VMs.
  455. func Example() {
  456. codeToShare := CompileLua("mylua.lua")
  457. a := lua.NewState()
  458. b := lua.NewState()
  459. c := lua.NewState()
  460. DoCompiledFile(a, codeToShare)
  461. DoCompiledFile(b, codeToShare)
  462. DoCompiledFile(c, codeToShare)
  463. }
  464. +++++++++++++++++++++++++++++++++++++++++
  465. Goroutines
  466. +++++++++++++++++++++++++++++++++++++++++
  467. The ``LState`` is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.
  468. Channels are represented by ``channel`` objects in GopherLua. And a ``channel`` table provides functions for performing channel operations.
  469. Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.
  470. - a thread(state)
  471. - a function
  472. - an userdata
  473. - a table with a metatable
  474. You **must not** send these objects from Go APIs to channels.
  475. .. code-block:: go
  476. func receiver(ch, quit chan lua.LValue) {
  477. L := lua.NewState()
  478. defer L.Close()
  479. L.SetGlobal("ch", lua.LChannel(ch))
  480. L.SetGlobal("quit", lua.LChannel(quit))
  481. if err := L.DoString(`
  482. local exit = false
  483. while not exit do
  484. channel.select(
  485. {"|<-", ch, function(ok, v)
  486. if not ok then
  487. print("channel closed")
  488. exit = true
  489. else
  490. print("received:", v)
  491. end
  492. end},
  493. {"|<-", quit, function(ok, v)
  494. print("quit")
  495. exit = true
  496. end}
  497. )
  498. end
  499. `); err != nil {
  500. panic(err)
  501. }
  502. }
  503. func sender(ch, quit chan lua.LValue) {
  504. L := lua.NewState()
  505. defer L.Close()
  506. L.SetGlobal("ch", lua.LChannel(ch))
  507. L.SetGlobal("quit", lua.LChannel(quit))
  508. if err := L.DoString(`
  509. ch:send("1")
  510. ch:send("2")
  511. `); err != nil {
  512. panic(err)
  513. }
  514. ch <- lua.LString("3")
  515. quit <- lua.LTrue
  516. }
  517. func main() {
  518. ch := make(chan lua.LValue)
  519. quit := make(chan lua.LValue)
  520. go receiver(ch, quit)
  521. go sender(ch, quit)
  522. time.Sleep(3 * time.Second)
  523. }
  524. '''''''''''''''
  525. Go API
  526. '''''''''''''''
  527. ``ToChannel``, ``CheckChannel``, ``OptChannel`` are available.
  528. Refer to `Go doc(LState methods) <http://godoc.org/github.com/yuin/gopher-lua>`_ for further information.
  529. '''''''''''''''
  530. Lua API
  531. '''''''''''''''
  532. - **channel.make([buf:int]) -> ch:channel**
  533. - Create new channel that has a buffer size of ``buf``. By default, ``buf`` is 0.
  534. - **channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}**
  535. - Same as the ``select`` statement in Go. It returns the index of the chosen case and, if that
  536. case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
  537. - ``case`` is a table that outlined below.
  538. - receiving: `{"|<-", ch:channel [, handler:func(ok, data:any)]}`
  539. - sending: `{"<-|", ch:channel, data:any [, handler:func(data:any)]}`
  540. - default: `{"default" [, handler:func()]}`
  541. ``channel.select`` examples:
  542. .. code-block:: lua
  543. local idx, recv, ok = channel.select(
  544. {"|<-", ch1},
  545. {"|<-", ch2}
  546. )
  547. if not ok then
  548. print("closed")
  549. elseif idx == 1 then -- received from ch1
  550. print(recv)
  551. elseif idx == 2 then -- received from ch2
  552. print(recv)
  553. end
  554. .. code-block:: lua
  555. channel.select(
  556. {"|<-", ch1, function(ok, data)
  557. print(ok, data)
  558. end},
  559. {"<-|", ch2, "value", function(data)
  560. print(data)
  561. end},
  562. {"default", function()
  563. print("default action")
  564. end}
  565. )
  566. - **channel:send(data:any)**
  567. - Send ``data`` over the channel.
  568. - **channel:receive() -> ok:bool, data:any**
  569. - Receive some data over the channel.
  570. - **channel:close()**
  571. - Close the channel.
  572. ''''''''''''''''''''''''''''''
  573. The LState pool pattern
  574. ''''''''''''''''''''''''''''''
  575. To create per-thread LState instances, You can use the ``sync.Pool`` like mechanism.
  576. .. code-block:: go
  577. type lStatePool struct {
  578. m sync.Mutex
  579. saved []*lua.LState
  580. }
  581. func (pl *lStatePool) Get() *lua.LState {
  582. pl.m.Lock()
  583. defer pl.m.Unlock()
  584. n := len(pl.saved)
  585. if n == 0 {
  586. return pl.New()
  587. }
  588. x := pl.saved[n-1]
  589. pl.saved = pl.saved[0 : n-1]
  590. return x
  591. }
  592. func (pl *lStatePool) New() *lua.LState {
  593. L := lua.NewState()
  594. // setting the L up here.
  595. // load scripts, set global variables, share channels, etc...
  596. return L
  597. }
  598. func (pl *lStatePool) Put(L *lua.LState) {
  599. pl.m.Lock()
  600. defer pl.m.Unlock()
  601. pl.saved = append(pl.saved, L)
  602. }
  603. func (pl *lStatePool) Shutdown() {
  604. for _, L := range pl.saved {
  605. L.Close()
  606. }
  607. }
  608. // Global LState pool
  609. var luaPool = &lStatePool{
  610. saved: make([]*lua.LState, 0, 4),
  611. }
  612. Now, you can get per-thread LState objects from the ``luaPool`` .
  613. .. code-block:: go
  614. func MyWorker() {
  615. L := luaPool.Get()
  616. defer luaPool.Put(L)
  617. /* your code here */
  618. }
  619. func main() {
  620. defer luaPool.Shutdown()
  621. go MyWorker()
  622. go MyWorker()
  623. /* etc... */
  624. }
  625. ----------------------------------------------------------------
  626. Differences between Lua and GopherLua
  627. ----------------------------------------------------------------
  628. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  629. Goroutines
  630. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  631. - GopherLua supports channel operations.
  632. - GopherLua has a type named ``channel``.
  633. - The ``channel`` table provides functions for performing channel operations.
  634. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  635. Unsupported functions
  636. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  637. - ``string.dump``
  638. - ``os.setlocale``
  639. - ``lua_Debug.namewhat``
  640. - ``package.loadlib``
  641. - debug hooks
  642. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  643. Miscellaneous notes
  644. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  645. - ``collectgarbage`` does not take any arguments and runs the garbage collector for the entire Go program.
  646. - ``file:setvbuf`` does not support a line buffering.
  647. - Daylight saving time is not supported.
  648. - GopherLua has a function to set an environment variable : ``os.setenv(name, value)``
  649. - GopherLua support ``goto`` and ``::label::`` statement in Lua5.2.
  650. - `goto` is a keyword and not a valid variable name.
  651. ----------------------------------------------------------------
  652. Standalone interpreter
  653. ----------------------------------------------------------------
  654. Lua has an interpreter called ``lua`` . GopherLua has an interpreter called ``glua`` .
  655. .. code-block:: bash
  656. go get github.com/yuin/gopher-lua/cmd/glua
  657. ``glua`` has same options as ``lua`` .
  658. ----------------------------------------------------------------
  659. How to Contribute
  660. ----------------------------------------------------------------
  661. See `Guidlines for contributors <https://github.com/yuin/gopher-lua/tree/master/.github/CONTRIBUTING.md>`_ .
  662. ----------------------------------------------------------------
  663. Libraries for GopherLua
  664. ----------------------------------------------------------------
  665. - `gopher-luar <https://github.com/layeh/gopher-luar>`_ : Simplifies data passing to and from gopher-lua
  666. - `gluamapper <https://github.com/yuin/gluamapper>`_ : Mapping a Lua table to a Go struct
  667. - `gluare <https://github.com/yuin/gluare>`_ : Regular expressions for gopher-lua
  668. - `gluahttp <https://github.com/cjoudrey/gluahttp>`_ : HTTP request module for gopher-lua
  669. - `gopher-json <https://github.com/layeh/gopher-json>`_ : A simple JSON encoder/decoder for gopher-lua
  670. - `gluayaml <https://github.com/kohkimakimoto/gluayaml>`_ : Yaml parser for gopher-lua
  671. - `glua-lfs <https://github.com/layeh/gopher-lfs>`_ : Partially implements the luafilesystem module for gopher-lua
  672. - `gluaurl <https://github.com/cjoudrey/gluaurl>`_ : A url parser/builder module for gopher-lua
  673. - `gluahttpscrape <https://github.com/felipejfc/gluahttpscrape>`_ : A simple HTML scraper module for gopher-lua
  674. - `gluaxmlpath <https://github.com/ailncode/gluaxmlpath>`_ : An xmlpath module for gopher-lua
  675. - `gmoonscript <https://github.com/rucuriousyet/gmoonscript>`_ : Moonscript Compiler for the Gopher Lua VM
  676. - `loguago <https://github.com/rucuriousyet/loguago>`_ : Zerolog wrapper for Gopher-Lua
  677. - `gluacrypto <https://github.com/tengattack/gluacrypto>`_ : A native Go implementation of crypto library for the GopherLua VM.
  678. - `gluasql <https://github.com/tengattack/gluasql>`_ : A native Go implementation of SQL client for the GopherLua VM.
  679. - `purr <https://github.com/leyafo/purr>`_ : A http mock testing tool.
  680. - `vadv/gopher-lua-libs <https://github.com/vadv/gopher-lua-libs>`_ : Some usefull libraries for GopherLua VM.
  681. - `gluasocket <https://gitlab.com/megalithic-llc/gluasocket>`_ : A native Go implementation of LuaSocket for the GopherLua VM.
  682. - `glua-async <https://github.com/CuberL/glua-async>`_ : An async/await implement for gopher-lua.
  683. - `gopherlua-debugger <https://github.com/edolphin-ydf/gopherlua-debugger>`_ : A debugger for gopher-lua
  684. - `gluamahonia <https://github.com/super1207/gluamahonia>`_ : An encoding converter for gopher-lua
  685. ----------------------------------------------------------------
  686. Donation
  687. ----------------------------------------------------------------
  688. BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB
  689. ----------------------------------------------------------------
  690. License
  691. ----------------------------------------------------------------
  692. MIT
  693. ----------------------------------------------------------------
  694. Author
  695. ----------------------------------------------------------------
  696. Yusuke Inuzuka