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 | $ lua > -- create an empty table and add some elements > t1 = {} > t1[1] = "moustache" > t1[2] = 3 > t1["brothers"] = true > -- more commonly, create the table and define elements > all at once > t2 = {[1] = "groucho", [3] = "chico", [5] = "harpo"} > t3 = {[t1[1]] = t2[1], accent = t2[3], horn = t2[5]} > t4 = {} > t4[t3] = "the marx brothers" > t5 = {characters = t2, marks = t3} > t6 = {["a night at the opera"] = "classic"} > -- make a reference and a string > i = t3 > s = "a night at the opera" > -- indices can be any Lua value > print(t1[1], t4[t3], t6[s]) moustache the marx brothers classic > -- the phrase table.string is the same as table["string"] > print(t3.horn, t3["horn"]) harpo harpo > -- indices can also be "multi-dimensional" > print (t5["marks"]["horn"], t5.marks.horn) harpo harpo > -- i points to the same table as t3 > = t4 the marx brothers > -- non-existent indices return nil values > print(t1[2], t2[2], t5.films) nil nil nil > -- even a function can be a key > t = {} > function t.add(i,j) >> return(i+j) >> end > print(t.add(1,2)) 3 > print(t['add'](1,2)) 3 > -- and another variation of a function as a key > t = {} > function v(x) >> print(x) >> end > t[v] = "The Big Store" > for key,value in t do key(value) end The Big Store |
1 2 3 | > table.foreachi(t1, print) 1 moustache 2 3 |
1 2 3 4 5 6 7 8 | > table.foreach(t2,print) 1 groucho 3 chico 5 harpo > table.foreach(t1,print) 1 moustache 2 3 brothers true |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |