mirror of
https://github.com/zyedidia/micro.git
synced 2026-03-18 14:57:18 +09:00
Start plugin support and plugin manager
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -28,10 +29,10 @@ func init() {
|
||||
}
|
||||
|
||||
// LoadFile loads a lua file
|
||||
func LoadFile(module string, file string, data string) error {
|
||||
pluginDef := "local P = {};" + module + " = P;setmetatable(" + module + ", {__index = _G});setfenv(1, P);"
|
||||
func LoadFile(module string, file string, data []byte) error {
|
||||
pluginDef := []byte("module(\"" + module + "\", package.seeall)")
|
||||
|
||||
if fn, err := L.Load(strings.NewReader(pluginDef+data), file); err != nil {
|
||||
if fn, err := L.Load(bytes.NewReader(append(pluginDef, data...)), file); err != nil {
|
||||
return err
|
||||
} else {
|
||||
L.Push(fn)
|
||||
|
||||
67
cmd/micro/lua/plugin.go
Normal file
67
cmd/micro/lua/plugin.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
var ErrNoSuchFunction = errors.New("No such function exists")
|
||||
|
||||
type Plugin struct {
|
||||
name string
|
||||
files []string
|
||||
}
|
||||
|
||||
func NewPluginFromDir(name string, dir string) (*Plugin, error) {
|
||||
files, err := ioutil.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p := new(Plugin)
|
||||
p.name = name
|
||||
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f.Name(), ".lua") {
|
||||
p.files = append(p.files, dir+f.Name())
|
||||
}
|
||||
}
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) Load() error {
|
||||
for _, f := range p.files {
|
||||
dat, err := ioutil.ReadFile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = LoadFile(p.name, f, dat)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) Call(fn string, args ...lua.LValue) (lua.LValue, error) {
|
||||
plug := L.GetGlobal(p.name)
|
||||
luafn := L.GetField(plug, fn)
|
||||
if luafn == lua.LNil {
|
||||
return nil, ErrNoSuchFunction
|
||||
}
|
||||
err := L.CallByParam(lua.P{
|
||||
Fn: luafn,
|
||||
NRet: 1,
|
||||
Protect: true,
|
||||
}, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret := L.Get(-1)
|
||||
L.Pop(1)
|
||||
return ret, nil
|
||||
}
|
||||
Reference in New Issue
Block a user