File: metatable.go

package info (click to toggle)
golang-layeh-gopher-luar 1.0.4-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 224 kB
  • sloc: makefile: 7
file content (44 lines) | stat: -rw-r--r-- 996 bytes parent folder | download | duplicates (2)
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
package luar

import (
	"reflect"

	"github.com/yuin/gopher-lua"
)

// Metatable is the Lua metatable for a Go type.
type Metatable struct {
	*lua.LTable
}

// MT returns the metatable for value's type. nil is returned if value's type
// does not use a custom metatable.
func MT(L *lua.LState, value interface{}) *Metatable {
	if value == nil {
		return nil
	}

	switch typ := reflect.TypeOf(value); typ.Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct:
		return &Metatable{
			LTable: getMetatable(L, typ),
		}
	}
	return nil
}

func (m *Metatable) method(name string) lua.LValue {
	methods := m.RawGetString("methods").(*lua.LTable)
	if fn := methods.RawGetString(name); fn != lua.LNil {
		return fn
	}
	return nil
}

func (m *Metatable) fieldIndex(name string) []int {
	fields := m.RawGetString("fields").(*lua.LTable)
	if index := fields.RawGetString(name); index != lua.LNil {
		return index.(*lua.LUserData).Value.([]int)
	}
	return nil
}