Hilbish/golibs/commander/commander.go

71 lines
1.6 KiB
Go
Raw Normal View History

package commander
import (
"hilbish/util"
2022-03-28 23:12:58 +00:00
rt "github.com/arnodel/golua/runtime"
"github.com/arnodel/golua/lib/packagelib"
"github.com/chuckpreslar/emission"
)
type Commander struct{
Events *emission.Emitter
2022-03-28 23:12:58 +00:00
Loader packagelib.Loader
}
func New() Commander {
2022-03-28 23:12:58 +00:00
c := Commander{
Events: emission.NewEmitter(),
}
2022-03-28 23:12:58 +00:00
c.Loader = packagelib.Loader{
Load: c.LoaderFunc,
Name: "commander",
}
return c
}
2022-03-28 23:12:58 +00:00
func (c *Commander) LoaderFunc(rtm *rt.Runtime) (rt.Value, func()) {
exports := map[string]util.LuaExport{
"register": util.LuaExport{c.cregister, 2, false},
"deregister": util.LuaExport{c.cderegister, 1, false},
}
2022-03-28 23:12:58 +00:00
mod := rt.NewTable()
util.SetExports(rtm, mod, exports)
// util.Document(L, mod, "Commander is Hilbish's custom command library, a way to write commands in Lua.")
2022-03-28 23:12:58 +00:00
return rt.TableValue(mod), nil
}
// register(name, cb)
// Register a command with `name` that runs `cb` when ran
// --- @param name string
// --- @param cb function
2022-03-28 23:12:58 +00:00
func (c *Commander) cregister(t *rt.Thread, ct *rt.GoCont) (rt.Cont, error) {
cmdName, cmd, err := util.HandleStrCallback(t, ct)
if err != nil {
return nil, err
}
c.Events.Emit("commandRegister", cmdName, cmd)
2022-03-28 23:12:58 +00:00
return ct.Next(), err
}
// deregister(name)
// Deregisters any command registered with `name`
// --- @param name string
2022-03-28 23:12:58 +00:00
func (c *Commander) cderegister(t *rt.Thread, ct *rt.GoCont) (rt.Cont, error) {
if err := ct.Check1Arg(); err != nil {
return nil, err
}
cmdName, err := ct.StringArg(0)
if err != nil {
return nil, err
}
c.Events.Emit("commandDeregister", cmdName)
2022-03-28 23:12:58 +00:00
return ct.Next(), err
}