github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/lua/tables.lua (about) 1 local t = {3, 2, 1, x = "abc", ["zz"] = 12} 2 print(t[1]) 3 --> =3 4 print(#t) 5 --> =3 6 t[4]=2 7 print(#t) 8 --> =4 9 print(t["x"] .. t.zz) 10 --> =abc12 11 12 t[6]=1 13 t[5]=1 14 print(#t) 15 --> =6 16 17 t[6]=nil 18 print(#t) 19 --> =5 20 21 t[4]=nil 22 t[5]=nil 23 print(#t) 24 --> =3 25 26 t[3.2] = 5 27 print(t[3.2]) 28 --> =5 29 30 t[5e2] = "hi" 31 print(t[500]) 32 --> =hi 33 34 print(#t) 35 --> =3 36 37 t.xxx = nil 38 print(t.xxx) 39 --> =nil 40 41 print(pcall(function() t[nil] = 2 end)) 42 --> ~false\t.*index is nil 43 44 print(pcall(function() t[0/0] = 2 end)) 45 --> ~false\t.*index is NaN 46 47 do 48 local t = {"x", "y"} 49 local a, x = next(t) 50 local b, y = next(t, a) 51 if a < b then 52 print(a..b, x..y) 53 else 54 print(b..a, y..x) 55 end 56 --> =12 xy 57 58 print(next(t, b)) 59 --> =nil 60 61 print(pcall(next, t, "abc")) 62 --> ~^false 63 64 t[b] = nil 65 print(next(t, a)) 66 --> =nil 67 68 print(next({})) 69 --> =nil 70 end 71 72 -- custom length as used in table module functions 73 do 74 local t = {"x", "y"} 75 debug.setmetatable(t, {__len=function() return 10 end}) 76 table.insert(t, 5) 77 print(t[11]) 78 --> =5 79 end 80 do 81 local t = {"x", "y"} 82 debug.setmetatable(t, {__len=function() return "hi" end}) 83 print(pcall(table.insert, t, 5)) 84 --> ~false\t.* 85 end 86 do 87 local t = {"x", "y"} 88 debug.setmetatable(t, {__len=function() error("haha") end}) 89 print(pcall(table.insert, t, 5)) 90 --> ~false\t.* haha 91 end