diff --git a/_example/library.go b/_example/library.go new file mode 100644 index 00000000..d968d82f --- /dev/null +++ b/_example/library.go @@ -0,0 +1,36 @@ +package main + +import "github.com/aarzilli/golua/lua" + +func test(L *lua.State) int { + println("hello!") + return 0 +} + +func test2(L *lua.State) int { + println("world!") + return 0 +} + +var funcs = map[string]lua.LuaGoFunction{ + "test": test, + "test2": test2, +} + +const code = ` + local example = require("example") + example.test() + example.test2() + ` + +func main() { + L := lua.NewState() + defer L.Close() + L.OpenLibs() + + L.RegisterLibrary("example", funcs) + + if err := L.DoString(code); err != nil { + panic(err) + } +} diff --git a/lua/lua.go b/lua/lua.go index b53303e9..bb20ca6f 100644 --- a/lua/lua.go +++ b/lua/lua.go @@ -438,6 +438,29 @@ func (L *State) Register(name string, f LuaGoFunction) { L.SetGlobal(name) } +// Registers a map of go functions as a library that can be accessed using "require("name")" +func (L *State) RegisterLibrary(name string, funcs map[string]LuaGoFunction) { + L.GetGlobal(name) + found := L.IsTable(-1) + if !found { + L.Pop(1) + L.CreateTable(0, len(funcs)) + } + + for fname, f := range funcs { + L.PushGoFunction(f) + L.SetField(-2, fname) + } + + if !found { + L.GetGlobal("package") + L.GetField(-1, "loaded") + L.PushValue(-3) + L.SetField(-2, name) + L.Pop(2) + } +} + // lua_setallocf func (L *State) SetAllocf(f Alloc) { L.allocfn = &f