github.com/dfcfw/lua@v0.0.0-20230325031207-0cc7ffb7b8b9/luar/config.go (about) 1 package luar 2 3 import ( 4 "reflect" 5 6 "github.com/dfcfw/lua" 7 ) 8 9 // Config is used to define luar behaviour for a particular *lua.LState. 10 type Config struct { 11 // The name generating function that defines under which names Go 12 // struct fields will be accessed. 13 // 14 // If nil, the default behaviour is used: 15 // - if the "luar" tag of the field is "", the field name and its name 16 // with a lowercase first letter is returned 17 // - if the tag is "-", no name is returned (i.e. the field is not 18 // accessible) 19 // - for any other tag value, that value is returned 20 FieldNames func(s reflect.Type, f reflect.StructField) []string 21 22 // The name generating function that defines under which names Go 23 // methods will be accessed. 24 // 25 // If nil, the default behaviour is used: 26 // - the method name and its name with a lowercase first letter 27 MethodNames func(t reflect.Type, m reflect.Method) []string 28 29 regular map[reflect.Type]*lua.LTable 30 types *lua.LTable 31 } 32 33 func newConfig() *Config { 34 return &Config{ 35 regular: make(map[reflect.Type]*lua.LTable), 36 } 37 } 38 39 // GetConfig returns the luar configuration options for the given *lua.LState. 40 func GetConfig(L *lua.LState) *Config { 41 const registryKey = "github.com/layeh/gopher-luar" 42 43 registry := L.Get(lua.RegistryIndex).(*lua.LTable) 44 lConfig, ok := registry.RawGetString(registryKey).(*lua.LUserData) 45 if !ok { 46 lConfig = L.NewUserData() 47 lConfig.Value = newConfig() 48 registry.RawSetString(registryKey, lConfig) 49 } 50 return lConfig.Value.(*Config) 51 } 52 53 func defaultFieldNames(s reflect.Type, f reflect.StructField) []string { 54 const tagName = "luar" 55 56 tag := f.Tag.Get(tagName) 57 if tag == "-" { 58 return nil 59 } 60 if tag != "" { 61 return []string{tag} 62 } 63 return []string{ 64 f.Name, 65 getUnexportedName(f.Name), 66 } 67 } 68 69 func defaultMethodNames(t reflect.Type, m reflect.Method) []string { 70 return []string{ 71 m.Name, 72 getUnexportedName(m.Name), 73 } 74 }