// Convert a Lua table to a map by using gluamapper. // If the map really is an array (all the keys are indices), return true. func table2mapinterface(luaTable *lua.LTable) (retmap map[interface{}]interface{}, isArray bool, err error) { var ( m = make(map[interface{}]interface{}) opt = gluamapper.Option{} indices []uint64 i, length uint64 ) // Catch a problem that may occur when converting the map value with gluamapper.ToGoValue defer func() { if r := recover(); r != nil { retmap = m err = errors.New("Could not represent Lua structure table as a map") return } }() luaTable.ForEach(func(tkey, tvalue lua.LValue) { if i, isNum := tkey.(lua.LNumber); isNum { indices = append(indices, uint64(i)) } // If tkey or tvalue is an LTable, give up m[gluamapper.ToGoValue(tkey, opt)] = gluamapper.ToGoValue(tvalue, opt) length++ }) // Report back as a map, not an array, if there are no elements if length == 0 { return m, false, nil } // Loop through every index that must be present in an array isAnArray := true for i = 1; i <= length; i++ { // The map must have this index in order to be an array hasIt := false for _, val := range indices { if val == i { hasIt = true break } } if !hasIt { isAnArray = false break } } return m, isAnArray, nil }
func mapper(tbl *lua.LTable) (map[interface{}]interface{}, error) { opt := gluamapper.Option{NameFunc: gluamapper.ToUpperCamelCase} mp, ok := gluamapper.ToGoValue(tbl, opt).(map[interface{}]interface{}) if !ok { return nil, errors.New("arguments #1 must be a table, but got an array") } return mp, nil }
func luaTemplate(L *lua.LState) int { tpl, err := template.New("").Parse(L.CheckString(1)) if err != nil { L.RaiseError(err.Error()) return 0 } gomap := gluamapper.ToGoValue(L.CheckTable(2), gluamapper.Option{NameFunc: gluamapper.Id}) var buf bytes.Buffer if err := tpl.Execute(&buf, gomap); err != nil { L.RaiseError(err.Error()) return 0 } L.Push(lua.LString(buf.String())) return 1 }