Hilbish/golibs/bait/bait.go

58 lines
1.4 KiB
Go
Raw Normal View History

2021-03-26 05:12:55 +00:00
package bait
import (
"fmt"
"hilbish/util"
2021-03-26 05:12:55 +00:00
"github.com/chuckpreslar/emission"
"github.com/yuin/gopher-lua"
2021-03-30 23:47:02 +00:00
"layeh.com/gopher-luar"
2021-03-26 05:12:55 +00:00
)
2021-03-30 23:47:02 +00:00
type Bait struct{
Em *emission.Emitter
}
2021-03-26 05:12:55 +00:00
func New() Bait {
emitter := emission.NewEmitter()
emitter.RecoverWith(func(hookname, hookfunc interface{}, err error) {
emitter.Off(hookname, hookfunc)
fmt.Println(err)
})
2021-03-30 23:47:02 +00:00
return Bait{
Em: emitter,
2021-03-30 23:47:02 +00:00
}
2021-03-26 05:12:55 +00:00
}
func (b *Bait) Loader(L *lua.LState) int {
2021-03-30 23:47:02 +00:00
mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{})
2021-11-22 23:58:30 +00:00
util.Document(L, mod,
`Bait is the event emitter for Hilbish. Why name it bait?
Because it throws hooks that you can catch (emits events
that you can listen to) and because why not, fun naming
is fun. This is what you will use if you want to listen
in on hooks to know when certain things have happened,
like when you've changed directory, a command has
failed, etc. To find all available hooks, see doc hooks.`)
L.SetField(mod, "throw", luar.New(L, b.bthrow))
L.SetField(mod, "catch", luar.New(L, b.bcatch))
2021-03-26 05:12:55 +00:00
L.Push(mod)
return 1
}
// throw(name, ...args)
// Throws a hook with `name` with the provided `args`
func (b *Bait) bthrow(name string, args ...interface{}) {
2021-03-30 23:47:02 +00:00
b.Em.Emit(name, args...)
}
// catch(name, cb)
// Catches a hook with `name`. Runs the `cb` when it is thrown
func (b *Bait) bcatch(name string, catcher func(...interface{})) {
2021-03-30 23:47:02 +00:00
b.Em.On(name, catcher)
}