-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfile.go
67 lines (57 loc) · 1.11 KB
/
file.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
package purr
import (
"io/ioutil"
"os"
lua "github.com/yuin/gopher-lua"
)
const luaFileTypeName = "FILE"
//lOpenFile open file as read only mode.
func lOpenFile(L *lua.LState) int {
filePath := L.CheckString(1)
file, err := os.Open(filePath)
if err != nil {
L.ArgError(1, err.Error())
return 0
}
ud := L.NewUserData()
ud.Value = file
L.SetMetatable(ud, L.GetTypeMetatable(luaFileTypeName))
L.Push(ud)
return 1
}
func lCloseFile(L *lua.LState) int {
f := checkFile(L)
f.Close()
return 0
}
func checkFile(L *lua.LState) *os.File {
ud := L.CheckUserData(1)
if v, ok := ud.Value.(*os.File); ok {
return v
}
L.ArgError(1, luaFileTypeName+" expected")
return nil
}
func lFileSize(L *lua.LState) int {
f := checkFile(L)
fi, err := f.Stat()
if err != nil {
L.ArgError(1, err.Error())
return 0
}
L.Push(lua.LNumber(fi.Size()))
return 1
}
func lFileBuffer(L *lua.LState) int {
f := checkFile(L)
b, err := ioutil.ReadAll(f)
if err != nil {
L.ArgError(1, err.Error())
return 0
}
ud := L.NewUserData()
ud.Value = b
L.SetMetatable(ud, L.GetTypeMetatable(luaBufferTypeName))
L.Push(ud)
return 1
}