Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

GopherLua: VM and compiler for Lua in Go.

Join the chat at https://gitter.im/yuin/gopher-lua

GopherLua is a Lua5.1 VM and compiler written in Go. GopherLua has a same goal with Lua: Be a scripting language with extensible semantics . It provides Go APIs that allow you to easily embed a scripting language to your Go host programs.

  • Be a scripting language with extensible semantics.
  • User-friendly Go API
    • The stack based API like the one used in the original Lua implementation will cause a performance improvements in GopherLua (It will reduce memory allocations and concrete type <-> interface conversions). GopherLua API is not the stack based API. GopherLua give preference to the user-friendliness over the performance.

GopherLua is not fast but not too slow, I think.

GopherLua has almost equivalent ( or little bit better ) performance as Python3 on micro benchmarks.

There are some benchmarks on the wiki page .

go get github.com/yuin/gopher-lua

GopherLua supports >= Go1.5.

GopherLua APIs perform in much the same way as Lua, but the stack is used only for passing arguments and receiving returned values.

GopherLua supports channel operations. See "Goroutines" section.

Import a package.

import (
"github.com/yuin/gopher-lua"
)

Run scripts in the VM.

L:=lua.NewState()
deferL.Close()
iferr:=L.DoString(`print("hello")`); err!=nil {
panic(err)
}
L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("hello.lua"); err!=nil {
panic(err)
}

Refer to Lua Reference Manual and Go doc for further information.

Note that elements that are not commented in Go doc equivalent to Lua Reference Manual , except GopherLua uses objects instead of Lua stack indices.

Data model

All data in a GopherLua program is an LValue . LValue is an interface type that has following methods.

  • String() string
  • Type() LValueType

Objects implement an LValue interface are

Type nameGo typeType() valueConstants
LNilType(constants)LTNilLNil
LBool(constants)LTBoolLTrue, LFalse
LNumberfloat64LTNumber-
LStringstringLTString-
LFunctionstruct pointerLTFunction-
LUserDatastruct pointerLTUserData-
LStatestruct pointerLTThread-
LTablestruct pointerLTTable-
LChannelchan LValueLTChannel-

You can test an object type in Go way(type assertion) or using a Type() value.

lv:=L.Get(-1) // get the value at the top of the stackifstr, ok:=lv.(lua.LString); ok {
// lv is LStringfmt.Println(string(str))
}
iflv.Type() !=lua.LTString {
panic("string required.")
}
lv:=L.Get(-1) // get the value at the top of the stackiftbl, ok:=lv.(*lua.LTable); ok {
// lv is LTablefmt.Println(L.ObjLen(tbl))
}

Note that LBool , LNumber , LString is not a pointer.

To test LNilType and LBool, You must use pre-defined constants.

lv:=L.Get(-1) // get the value at the top of the stackiflv==lua.LTrue { // correct
}
ifbl, ok:=lv.(lua.LBool); ok&&bool(bl) { // wrong
}

In Lua, both nil and false make a condition false. LVIsFalse and LVAsBool implement this specification.

lv:=L.Get(-1) // get the value at the top of the stackiflua.LVIsFalse(lv) { // lv is nil or false
}
iflua.LVAsBool(lv) { // lv is neither nil nor false
}

Objects that based on go structs(LFunction. LUserData, LTable) have some public methods and fields. You can use these methods and fields for performance and debugging, but there are some limitations.

  • Metatable does not work.
  • No error handlings.

Callstack & Registry size

Size of the callstack & registry is fixed for mainly performance. You can change the default size of the callstack & registry.

lua.RegistrySize=1024*20lua.CallStackSize=1024L:=lua.NewState()
deferL.Close()

You can also create an LState object that has the callstack & registry size specified by Options .

L:=lua.NewState(lua.Options{
CallStackSize: 120,
RegistrySize: 120*20,
})

An LState object that has been created by *LState#NewThread() inherits the callstack & registry size from the parent LState object.

Miscellaneous lua.NewState options

  • Options.SkipOpenLibs bool(default false)
    • By default, GopherLua opens all built-in libraries when new LState is created.
    • You can skip this behaviour by setting this to true .
    • Using the various OpenXXX(L *LState) int functions you can open only those libraries that you require, for an example see below.
  • Options.IncludeGoStackTrace bool(default false)
    • By default, GopherLua does not show Go stack traces when panics occur.
    • You can get Go stack traces by setting this to true .

API

Refer to Lua Reference Manual and Go doc(LState methods) for further information.

Calling Go from Lua

funcDouble(L*lua.LState) int {
lv:=L.ToInt(1) /* get argument */L.Push(lua.LNumber(lv*2)) /* push result */return1/* number of results */
}
funcmain() {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("double", L.NewFunction(Double)) /* Original lua_setglobal uses stack... */
}
print(double(20)) -- > "40"

Any function registered with GopherLua is a lua.LGFunction, defined in value.go

typeLGFunctionfunc(*LState) int

Working with coroutines.

co, _:=L.NewThread() /* create a new thread */fn:=L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */for {
st, err, values:=L.Resume(co, fn)
ifst==lua.ResumeError {
fmt.Println("yield break(error)")
fmt.Println(err.Error())
break
}
fori, lv:=rangevalues {
fmt.Printf("%v : %v\n", i, lv)
}
ifst==lua.ResumeOK {
fmt.Println("yield break(ok)")
break
}
}

Opening a subset of builtin modules

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.

main.go

funcmain() {
L:=lua.NewState(lua.Options{SkipOpenLibs: true})
deferL.Close()
for_, pair:=range []struct {
nstringf lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
} {
iferr:=L.CallByParam(lua.P{
Fn: L.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err!=nil {
panic(err)
}
}
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

Creating a module by Go

mymodule.go

package mymodule
import (
"github.com/yuin/gopher-lua"
)
funcLoader(L*lua.LState) int {
// register functions to the tablemod:=L.SetFuncs(L.NewTable(), exports)
// register other stuffL.SetField(mod, "name", lua.LString("value"))
// returns the moduleL.Push(mod)
return1
}
varexports=map[string]lua.LGFunction{
"myfunc": myfunc,
}
funcmyfunc(L*lua.LState) int {
return0
}

mymain.go

package main
import (
"./mymodule""github.com/yuin/gopher-lua"
)
funcmain() {
L:=lua.NewState()
deferL.Close()
L.PreloadModule("mymodule", mymodule.Loader)
iferr:=L.DoFile("main.lua"); err!=nil {
panic(err)
}
}

main.lua

localm=require("mymodule")
m.myfunc()
print(m.name)

Calling Lua from Go

L:=lua.NewState()
deferL.Close()
iferr:=L.DoFile("double.lua"); err!=nil {
panic(err)
}
iferr:=L.CallByParam(lua.P{
Fn: L.GetGlobal("double"),
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err!=nil {
panic(err)
}
ret:=L.Get(-1) // returned valueL.Pop(1) // remove received value

If Protect is false, GopherLua will panic instead of returning an error value.

User-Defined types

You can extend GopherLua with new types written in Go. LUserData is provided for this purpose.

typePersonstruct {
Namestring
}
constluaPersonTypeName="person"// Registers my person type to given L.funcregisterPersonType(L*lua.LState) {
mt:=L.NewTypeMetatable(luaPersonTypeName)
L.SetGlobal("person", mt)
// static attributesL.SetField(mt, "new", L.NewFunction(newPerson))
// methodsL.SetField(mt, "__index", L.SetFuncs(L.NewTable(), personMethods))
}
// ConstructorfuncnewPerson(L*lua.LState) int {
person:=&Person{L.CheckString(1)}
ud:=L.NewUserData()
ud.Value=personL.SetMetatable(ud, L.GetTypeMetatable(luaPersonTypeName))
L.Push(ud)
return1
}
// Checks whether the first lua argument is a *LUserData with *Person and returns this *Person.funccheckPerson(L*lua.LState) *Person {
ud:=L.CheckUserData(1)
ifv, ok:=ud.Value.(*Person); ok {
returnv
}
L.ArgError(1, "person expected")
returnnil
}
varpersonMethods=map[string]lua.LGFunction{
"name": personGetSetName,
}
// Getter and setter for the Person#NamefuncpersonGetSetName(L*lua.LState) int {
p:=checkPerson(L)
ifL.GetTop() ==2 {
p.Name=L.CheckString(2)
return0
}
L.Push(lua.LString(p.Name))
return1
}
funcmain() {
L:=lua.NewState()
deferL.Close()
registerPersonType(L)
iferr:=L.DoString(` p = person.new("Steeve") print(p:name()) -- "Steeve" p:name("Alice") print(p:name()) -- "Alice" `); err!=nil {
panic(err)
}
}

Terminating a running LState

GopherLua supports the Go Concurrency Patterns: Context .

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithTimeout(context.Background(), 1*time.Second)
defercancel()
// set the context to our LStateL.SetContext(ctx)
err:=L.DoString(` local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end sleep(3)`)
// err.Error() contains "context deadline exceeded"

With coroutines

L:=lua.NewState()
deferL.Close()
ctx, cancel:=context.WithCancel(context.Background())
L.SetContext(ctx)
defercancel()
L.DoString(` function coro() local i = 0 while true do coroutine.yield(i) i = i+1 end return i end`)
co, cocancel:=L.NewThread()
defercocancel()
fn:=L.GetGlobal("coro").(*LFunction)
_, err, values:=L.Resume(co, fn) // err is nilcancel() // cancel the parent context_, err, values=L.Resume(co, fn) // err is NOT nil : child context was canceled

Note that using a context causes performance degradation.

time ./glua-with-context.exe fib.lua
9227465
0.01s user 0.11s system 1% cpu 7.505 total
time ./glua-without-context.exe fib.lua
9227465
0.01s user 0.01s system 0% cpu 5.306 total

Goroutines

The LState is not goroutine-safe. It is recommended to use one LState per goroutine and communicate between goroutines by using channels.

Channels are represented by channel objects in GopherLua. And a channel table provides functions for performing channel operations.

Some objects can not be sent over channels due to having non-goroutine-safe objects inside itself.

  • a thread(state)
  • a function
  • an userdata
  • a table with a metatable

You must not send these objects from Go APIs to channels.

funcreceiver(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err!=nil {
panic(err)
}
}
funcsender(ch, quitchan lua.LValue) {
L:=lua.NewState()
deferL.Close()
L.SetGlobal("ch", lua.LChannel(ch))
L.SetGlobal("quit", lua.LChannel(quit))
iferr:=L.DoString(` ch:send("1") ch:send("2") `); err!=nil {
panic(err)
}
ch<-lua.LString("3")
quit<-lua.LTrue
}
funcmain() {
ch:=make(chan lua.LValue)
quit:=make(chan lua.LValue)
goreceiver(ch, quit)
gosender(ch, quit)
time.Sleep(3*time.Second)
}
Go API

ToChannel, CheckChannel, OptChannel are available.

Refer to Go doc(LState methods) for further information.

Lua API
  • channel.make([buf:int]) -> ch:channel
    • Create new channel that has a buffer size of buf. By default, buf is 0.
  • channel.select(case:table [, case:table, case:table ...]) -> {index:int, recv:any, ok}
    • Same as the select statement in Go. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the channel has been closed.
    • case is a table that outlined below.
      • receiving: {"|<-", ch:channel [, handler:func(ok, data:any)]}
      • sending: {"<-|", ch:channel, data:any [, handler:func(data:any)]}
      • default: {"default" [, handler:func()]}

channel.select examples:

localidx, recv, ok=channel.select(
{"|<-", ch1},
{"|<-", ch2}
)
ifnotokthenprint("closed")
elseifidx==1then-- received from ch1print(recv)
elseifidx==2then-- received from ch2print(recv)
end
channel.select(
{"|<-", ch1, function(ok, data)
print(ok, data)
end},
{"<-|", ch2, "value", function(data)
print(data)
end},
{"default", function()
print("default action")
end}
)
  • channel:send(data:any)
    • Send data over the channel.
  • channel:receive() -> ok:bool, data:any
    • Receive some data over the channel.
  • channel:close()
    • Close the channel.
The LState pool pattern

To create per-thread LState instances, You can use the sync.Pool like mechanism.

typelStatePoolstruct {
m sync.Mutexsaved []*lua.LState
}
func (pl*lStatePool) Get() *lua.LState {
pl.m.Lock()
deferpl.m.Unlock()
n:=len(pl.saved)
ifn==0 {
returnpl.New()
}
x:=pl.saved[n-1]
pl.saved=pl.saved[0 : n-1]
returnx
}
func (pl*lStatePool) New() *lua.LState {
L:=lua.NewState()
// setting the L up here.// load scripts, set global variables, share channels, etc...returnL
}
func (pl*lStatePool) Put(L*lua.LState) {
pl.m.Lock()
deferpl.m.Unlock()
pl.saved=append(pl.saved, L)
}
func (pl*lStatePool) Shutdown() {
for_, L:=rangepl.saved {
L.Close()
}
}
// Global LState poolvarluaPool=&lStatePool{
saved: make([]*lua.LState, 0, 4),
}

Now, you can get per-thread LState objects from the luaPool .

funcMyWorker() {
L:=luaPool.Get()
deferluaPool.Put(L)
/* your code here */
}
funcmain() {
deferluaPool.Shutdown()
goMyWorker()
goMyWorker()
/* etc... */
}

Goroutines

  • GopherLua supports channel operations.
    • GopherLua has a type named channel.
    • The channel table provides functions for performing channel operations.

Unsupported functions

  • string.dump
  • os.setlocale
  • lua_Debug.namewhat
  • package.loadlib
  • debug hooks

Miscellaneous notes

  • collectgarbage does not take any arguments and runs the garbage collector for the entire Go program.
  • file:setvbuf does not support a line buffering.
  • Daylight saving time is not supported.
  • GopherLua has a function to set an environment variable : os.setenv(name, value)

Lua has an interpreter called lua . GopherLua has an interpreter called glua .

go get github.com/yuin/gopher-lua/cmd/glua

glua has same options as lua .

See Guidlines for contributors .

  • gopher-luar : Custom type reflection for gopher-lua
  • gluamapper : Mapping a Lua table to a Go struct
  • gluare : Regular expressions for gopher-lua
  • gluahttp : HTTP request module for gopher-lua
  • gopher-json : A simple JSON encoder/decoder for gopher-lua
  • gluayaml : Yaml parser for gopher-lua
  • glua-lfs : Partially implements the luafilesystem module for gopher-lua
  • gluaurl : A url parser/builder module for gopher-lua
  • gluahttpscrape : A simple HTML scraper module for gopher-lua
  • gluaxmlpath : An xmlpath module for gopher-lua

BTC: 1NEDSyUmo4SMTDP83JJQSWi1MvQUGGNMZB

MIT

Yusuke Inuzuka

About

GopherLua: VM and compiler for Lua in Go

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages