summaryrefslogtreecommitdiff
path: root/lua.go
blob: a150e27f169626f47e06c70109c076f7eb30b6f9 (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main

/*
#cgo LDFLAGS: -llua
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

extern int luna_run_go_func(uintptr_t);

static inline int luna_run(lua_State *l) {
	return luna_run_go_func(lua_tonumber(l, lua_upvalueindex(1)));
}

static inline void luna_push_function(lua_State *l, uintptr_t f) {
	lua_pushinteger(l, f);
	lua_pushcclosure(l, luna_run, 1);
}
*/
import "C"
import (
	"errors"
	"fmt"
	"runtime/cgo"
	"unsafe"
)

type LuaRef C.longlong
// Lua is a wrapper around C Lua state with several conveniences.
type Lua struct {
	l *C.lua_State
}

//export luna_run_go_func
// luna_run_go_func calls a Go function from C/Lua.
func luna_run_go_func(f C.uintptr_t) C.int {
	fn := cgo.Handle(f).Value().(func() int)
	return C.int(fn())
}

// Start opens the Lua context with all built-in libraries.
func (l *Lua) Start() {
	l.l = C.luaL_newstate()
	C.luaL_openlibs(l.l)
}

// Close closes the Lua context.
func (l *Lua) Close() {
	C.lua_close(l.l)
}

// Require loads and executes the file pushing results onto the Lua stack.
func (l *Lua) Require(file string) error {
	if !l.LoadFile(file) {
		errMsg := l.ToString(-1)
		l.Pop(1)
		return errors.New("could not open the file:\n" + errMsg)
	}
	err := l.PCall(0, C.LUA_MULTRET)
	if err != nil {
		return errors.New("could not execute the file:\n" + err.Error())
	}
	return nil
}

// PCall calls a function with the stack index (-nargs - 1) expecting nresults
// number of results.
func (l *Lua) PCall(nargs int, nresults int) error {
	res := C.lua_pcallk(l.l, C.int(nargs), C.int(nresults), 0, 0, nil)
	if res != C.LUA_OK {
		errMsg := l.ToString(-1)
		l.Pop(1)
		return errors.New(errMsg)
	}
	return nil
}

// LoadFile loads the file code in the current Lua context.
func (l *Lua) LoadFile(file string) bool {
	cstr := C.CString(file)
	defer C.free(unsafe.Pointer(cstr))
	res := C.luaL_loadfilex(l.l, cstr, nil)
	return res == C.LUA_OK
}

// StackLen returns the length of the Lua stack.
func (l *Lua) StackLen() int {
	return int(C.lua_gettop(l.l))
}

// ToInt converts a stack value with stack index into a string.
func (l *Lua) ToString(index int) string {
	return C.GoString(C.lua_tolstring(l.l, C.int(index), nil))
}

// ToInt converts a stack value with stack index -1 into a number.
func (l *Lua) ToInt(index int) int {
	return int(C.lua_tonumberx(l.l, C.int(index), nil))
}

// PopToRef pops the item (stack offset -1) from the stack and then stores it
// in the registry.
func (l *Lua) PopToRef() LuaRef {
	return LuaRef(C.luaL_ref(l.l, C.LUA_REGISTRYINDEX))
}

// Pop pops N items from the Lua stack.
func (l *Lua) Pop(n int) {
	C.lua_settop(l.l, C.int(-n - 1))
}

// PushNumber pushes tnil onto the Lua stack.
func (l *Lua) PushNil() {
	C.lua_pushnil(l.l)
}

// PushNumber pushes the number onto the Lua stack.
func (l *Lua) PushNumber(num int) {
	C.lua_pushnumber(l.l, C.double(num))
}

// PushString pushes the string onto the Lua stack.
func (l *Lua) PushString(str string) {
	cstr := C.CString(str)
	defer C.free(unsafe.Pointer(cstr))
	C.lua_pushstring(l.l, cstr)
}

// PushGoFunction pushes a Go function onto the Lua stack so it's possible to
// call it from Lua. You may need to delete returned handle with .Delete()
// method later.
func (l *Lua) PushGoFunction(f func (l *Lua) int) cgo.Handle {
	h := cgo.NewHandle(func () int {
		return f(l)
	})
	C.luna_push_function(l.l, C.uintptr_t(h))
	return h
}

// CreateTable pushes a new Lua table onto the stack.
func (l *Lua) CreateTable(len int) {
	C.lua_createtable(l.l, 0, C.int(len))
}

// SetTableItem adds a value (stack offset -1) to a table (offset -2) under
// the specified key.
func (l *Lua) SetTableItem(key string) {
	cstr := C.CString(key)
	defer C.free(unsafe.Pointer(cstr))
	C.lua_setfield(l.l, -2, C.CString(key))
}

// PushStringTable pushes string->string table onto the stack.
func (l *Lua) PushStringTable(table map[string]string) {
	l.CreateTable(len(table))
	for k, v := range table {
		l.PushString(v)
		C.lua_setfield(l.l, -2, C.CString(k))
	}
}

// PushFromRef pushes a value from registry ref onto the stack.
func (l *Lua) PushFromRef(ref LuaRef) {
	C.lua_rawgeti(l.l, C.LUA_REGISTRYINDEX, C.longlong(ref));
}

// IsString checks if the stack contains a string under the given index.
func (l *Lua) IsString(index int) bool {
	return C.lua_isstring(l.l, C.int(index)) == 1
}

// IsNumber checks if the stack contains a number (both int and float) under
// the given index.
func (l *Lua) IsNumber(index int) bool {
	return C.lua_isnumber(l.l, C.int(index)) == 1
}

// IsFunction checks if the stack contains a function under the given index.
func (l *Lua) IsFunction(index int) bool {
	return C.lua_type(l.l, C.int(index)) == C.LUA_TFUNCTION
}

// IsTable checks if the stack contains a table under the given index.
func (l *Lua) IsTable(index int) bool {
	return C.lua_type(l.l, C.int(index)) == C.LUA_TTABLE
}

// Next advances a table iterator at the stack index -2.
func (l *Lua) Next() bool {
	return C.lua_next(l.l, -2) != 0
}

// LoadString loads and executes the code in the current Lua context.
func (l *Lua) LoadString(code string) error {
	cstr := C.CString(code)
	defer C.free(unsafe.Pointer(cstr))
	if C.luaL_loadstring(l.l, cstr) != C.LUA_OK {
		errMsg := l.ToString(-1)
		l.Pop(1)
		return errors.New(errMsg)
	}
	err := l.PCall(0, 0)
	if err != nil {
		return err
	}
	l.Pop(l.StackLen())
	return nil
}

// RestoreStackFunc remembers the Lua stack size and then restores it when a
// returned function is called. It's a helper function to avoid stack leakage.
func (l *Lua) RestoreStackFunc() func () {
	before := l.StackLen()
	return func () {
		after := l.StackLen()
		diff := after - before
		if diff == 0 {
			return
		} else if diff < 0 {
			msg := fmt.Sprintf(
				"too many stack pops: len before: %d, after: %d\n",
				before,
				after,
			)
			panic(msg)
		}
		C.lua_settop(l.l, C.int(before))
	}
}

// SetGlobal sets a global value at the -1 stack index with the name.
func (l *Lua) SetGlobal(name string) {
	cstr := C.CString(name)
	defer C.free(unsafe.Pointer(cstr))
	C.lua_setglobal(l.l, cstr)
}

// GetGlobal gets a global value under the name.
func (l *Lua) GetGlobal(name string) {
	cstr := C.CString(name)
	defer C.free(unsafe.Pointer(cstr))
	C.lua_getglobal(l.l, cstr)
}