2021-10-16 16:40:53 +00:00
|
|
|
package util
|
|
|
|
|
2022-03-28 02:14:53 +00:00
|
|
|
import (
|
2022-03-28 21:40:36 +00:00
|
|
|
"os"
|
|
|
|
|
2022-03-28 02:14:53 +00:00
|
|
|
"github.com/yuin/gopher-lua"
|
|
|
|
rt "github.com/arnodel/golua/runtime"
|
|
|
|
)
|
2021-10-16 16:40:53 +00:00
|
|
|
|
2021-11-22 23:59:28 +00:00
|
|
|
// Document adds a documentation string to a module.
|
|
|
|
// It is accessible via the __doc metatable.
|
2021-10-16 16:40:53 +00:00
|
|
|
func Document(L *lua.LState, module lua.LValue, doc string) {
|
2022-03-28 02:14:53 +00:00
|
|
|
/*
|
2021-11-22 23:59:28 +00:00
|
|
|
mt := L.GetMetatable(module)
|
|
|
|
if mt == lua.LNil {
|
|
|
|
mt = L.NewTable()
|
|
|
|
L.SetMetatable(module, mt)
|
|
|
|
}
|
2021-10-16 16:40:53 +00:00
|
|
|
L.SetField(mt, "__doc", lua.LString(doc))
|
2022-03-28 02:14:53 +00:00
|
|
|
*/
|
2021-11-22 23:59:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetField sets a field in a table, adding docs for it.
|
|
|
|
// It is accessible via the __docProp metatable. It is a table of the names of the fields.
|
2022-03-28 02:14:53 +00:00
|
|
|
func SetField(rtm *rt.Runtime, module *rt.Table, field string, value rt.Value, doc string) {
|
|
|
|
mt := module.Metatable()
|
|
|
|
|
|
|
|
if mt == nil {
|
|
|
|
mt = rt.NewTable()
|
|
|
|
docProp := rt.NewTable()
|
|
|
|
mt.Set(rt.StringValue("__docProp"), rt.TableValue(docProp))
|
2021-11-23 00:19:36 +00:00
|
|
|
|
2022-03-28 02:14:53 +00:00
|
|
|
module.SetMetatable(mt)
|
2021-11-23 00:19:36 +00:00
|
|
|
}
|
2022-03-28 02:14:53 +00:00
|
|
|
docProp := mt.Get(rt.StringValue("__docProp"))
|
2021-10-16 16:40:53 +00:00
|
|
|
|
2022-03-28 02:14:53 +00:00
|
|
|
docProp.AsTable().Set(rt.StringValue(field), rt.StringValue(doc))
|
|
|
|
module.Set(rt.StringValue(field), value)
|
2021-10-16 16:40:53 +00:00
|
|
|
}
|
2021-11-23 00:19:36 +00:00
|
|
|
|
2022-03-28 21:40:36 +00:00
|
|
|
func DoString(rtm *rt.Runtime, code string) error {
|
|
|
|
chunk, err := rtm.CompileAndLoadLuaChunk("", []byte(code), rt.TableValue(rtm.GlobalEnv()))
|
|
|
|
if chunk != nil {
|
|
|
|
_, err = rt.Call1(rtm.MainThread(), rt.FunctionValue(chunk))
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func DoFile(rtm *rt.Runtime, filename string) error {
|
|
|
|
data, err := os.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return DoString(rtm, string(data))
|
|
|
|
}
|
2022-03-28 23:12:13 +00:00
|
|
|
|
|
|
|
func HandleStrCallback(t *rt.Thread, c *rt.GoCont) (string, *rt.Closure, error) {
|
|
|
|
if err := c.CheckNArgs(2); err != nil {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
|
|
|
name, err := c.StringArg(0)
|
|
|
|
if err != nil {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
|
|
|
cb, err := c.ClosureArg(1)
|
|
|
|
if err != nil {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return name, cb, err
|
|
|
|
}
|