charlang/example/map.char
Copy
// declare an empty map a := {} // all keys will be converted to string type, values keep their original types a["Num"] = 3 a[5] = "abc" a[-1] = true a["ary"] = [1, "xyz", false] a[false] = "not true" a.Item1 = "item 1" pln(a) // length is the number of key-value pairs in the map pl("length of a: %v", len(a)) // index by dot pl("a.Num: %v", a.Num) // index by square brackets a["Num"]++ pln(a["Num"]) // slice pln(a[5][2:3]) a[5] = a[5] + a[5] // slice to end a[5] = a[5][1:] pl("a[5]: %v", a[5]) // slice from begining pln(a[5][:2]) // iterate for k, v in a { println("[", k, "]:", v) } pln("---") // declare map with initial values b := {"intItem": 12, "floatItem": 5.6, "boolItem": true, "stringItem": "str1", "arrayItem": ["array", "in", "map"], "mapItem": {"map": 1, "in": "map"}} plt(b) pln("---") c := {} // all keys will be converted to string type c[3] = "3" c[18] = "abc" c[-198] = "true" pl("c: %v", c) v1 := c[18] if v1 == undefined { println("v1:", v1) } // index with non-existent key v2 := c[19] if v2 == undefined { println("v2:", v2) } // remove key-value pair delete(c, 18) println("c:", c) // use methods c.Set("new", true) println("c:", c) rs := c.set("another") println("rs:", rs) println(`c["new"]`, c.get("new")) pl(`c["none"]: %v`, c.get("none")) pln("size:", c.size()) pln("keys:", c.keys()) pln("values:", c.values()) pln("toOrdered:", c.toOrdered()) try { pln("unknown method:", c.unknown()) } catch e { pln("exception:", e) } finally { pln("do finally") }