This repository has been archived by the owner on Dec 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
86 lines (75 loc) · 1.81 KB
/
loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/jiyeyuran/go-eventemitter"
lua "github.com/yuin/gopher-lua"
)
var (
em = eventemitter.NewEventEmitter()
)
type testPost struct {
ID int
Name string
Email string
Subject string
Message string
}
func loadObjects() {
state.SetGlobal("addListener", state.NewFunction(func(l *lua.LState) int {
name := l.ToString(1)
fmt.Println("Adding listener for", name)
cb := l.ToFunction(2)
em.On(name, func(interfaces ...interface{}) {
if len(interfaces) != 1 {
return
}
data := l.NewTable()
// there might be a simpler/automatic way to do this, but for now at least this'll have to do
postReflect := reflect.ValueOf(interfaces[0])
postType := postReflect.Type()
numFields := postReflect.NumField()
for i := 0; i < numFields; i++ {
field := postReflect.Field(i)
switch field.Kind() {
case reflect.Int:
fallthrough
case reflect.Float32:
fallthrough
case reflect.Float64:
data.RawSetString(postType.Field(i).Name, lua.LNumber(field.Int()))
case reflect.String:
data.RawSetString(postType.Field(i).Name, lua.LString(field.String()))
}
}
err := l.CallByParam(lua.P{
Fn: cb,
}, data)
if err != nil {
panic(err.Error())
}
})
return 0
}))
state.SetGlobal("doEvents", state.NewFunction(func(l *lua.LState) int {
fmt.Println("calling doEvents()")
em.Emit("post-received", testPost{
ID: 99,
Name: "Poster",
Email: "noko",
Subject: "Test post",
Message: "Blah blah blah",
})
return 0
}))
}
func loadPlugins(fullpath string, info os.FileInfo, err error) error {
if info.IsDir() || strings.ToLower(filepath.Ext(fullpath)) != ".lua" {
return nil
}
fmt.Println("Running file", fullpath)
return state.DoFile(fullpath)
}