Skip to content

Commit

Permalink
Add helper function to easily create lua libraries (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
MrNavaStar authored Oct 31, 2024
1 parent dc21732 commit 1841fa0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
36 changes: 36 additions & 0 deletions _example/library.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
23 changes: 23 additions & 0 deletions lua/lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 1841fa0

Please sign in to comment.