-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathapi.go
76 lines (68 loc) · 1.41 KB
/
api.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
// Package tac implements file scanner (from end to up) functionality for lua.
package tac
import (
"os"
lua "github.com/yuin/gopher-lua"
)
type luaTac struct {
filename string
fd *os.File
scanner *tacScanner
}
func checkTac(L *lua.LState, n int) *luaTac {
ud := L.CheckUserData(1)
if v, ok := ud.Value.(*luaTac); ok {
return v
}
L.ArgError(1, "tac expected")
return nil
}
func (t *luaTac) open() error {
fd, err := os.Open(t.filename)
if err != nil {
return err
}
t.fd = fd
t.scanner = newTacScanner(fd)
return nil
}
// Open lua tac.open(filename) open filename for tac scan returns (tac_ud, err)
func Open(L *lua.LState) int {
t := &luaTac{filename: L.CheckString(1)}
if err := t.open(); err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
ud := L.NewUserData()
ud.Value = t
L.SetMetatable(ud, L.GetTypeMetatable("tac_ud"))
L.Push(ud)
return 1
}
// Line lua tac_ud:line() return next upper line: string or nil
func Line(L *lua.LState) int {
t := checkTac(L, 1)
if t.scanner == nil {
L.RaiseError("tac not initialized")
return 0
}
if t.scanner.scan() {
text := t.scanner.text()
L.Push(lua.LString(text))
return 1
}
L.Push(lua.LNil)
return 1
}
// Close lua tac_ud:close() close current file for tac
func Close(L *lua.LState) int {
t := checkTac(L, 1)
if t.fd == nil {
L.RaiseError("tac not initialized")
return 0
}
t.fd.Close()
t = nil
return 0
}