Byron's log
‹‹ back
Lua 冲锋记笔(2)
Create Time : 2011-07-08 16:08:58
Modify Time : 2011-07-08 16:50:48
在查看正方前,深入了解,和正确了解lua最好是这一篇官方的英文文档TablesTutorial

数组的表现形式

要记住,请记住,lua的table数值索引下标是以1开始,而不是各种高级语言中以0开始,当索引超出边界时,不会中断错误,而是返回一个nil。 > t = { 1,1,2,3,5,8,13 } > print( t[1] ) 1 > print( t[0] ) nil > print( t[4] ) 3 在统计数组长度时,有一个很有趣的问题,它类似C语言中的字符串中出现\0标识字符串结束一样。在下例中实际y数组有5位长度,可是第四位被赋值为nil后,发生了截断。 > for i,v in ipairs(y) do print(i,v) end 1 1 2 2 3 3 4 0 5 55 > y[4] = nil > for i,v in ipairs(y) do print(i,v) end 1 1 2 2 3 3 添加插入元素操作有两种形式,一种是采用[]的方法,一定是用table.insert方法。 []方式 > for i,v in ipairs(y) do print(i,v) end 1 1 2 2 3 end > y[#y+1] = "append" > for i,v in ipairs(y) do print(i,v) end 1 1 2 2 3 end 4 append 5 55 table.insert方式 > table.insert(t,21) > = # t 8 > = t[7], t[8] 13 21 or > table.insert(t,4,99) > = t[3], t[4], t[5] 2 99 3 > table.remove(t,4) > = t[3], t[4], t[5] 2 3 5

字典的表现形式

通俗的说,table的字典表现形式就是php中的字面量索引数组,就是python中的dict。table的申明方式比较像python的tuple申明。 > t = { apple="green", orange="orange", banana="yellow" } > for k,v in pairs(t) do print(k,v) end apple green orange orange banana yellow 当然,它可以像javascript/python中的object一样用符号(.)来操作字面量下标,同样也可以像php和其它传统字面下标操作使用符号([])。 > t.melon = "green" > t["strawberry"] = "red" > for k,v in pairs(t) do print(k,v) end melon green strawberry red apple green orange orange banana yellow 所以结论是,其实数值索引下标就是字符索引下标的一种表现形试。因为他们同时可以用[string]=value和[number]=value的方式赋值。 > t = { 3,6,9 } -- is the same as... > t = { [1]=3, [2]=6, [3]=9 } -- is the same as... > t = {} t[1]=3 t[2]=6 t[3]=9 索引键值的引用 通常lua并不限制你的下标索引是什么类弄,聊了一个数值、字符串,它也可以是某中类型。如下例。 > a = { [{1,2,3}]="yadda" } -- construct a table where the element has a table key > for k,v in pairs(a) do print(k,v) end -- display the table contents: key-value pairs table: 0035BBC8 yadda > = a[{1,2,3}] -- display the element value nil 但是你必须注意的是,如果你使用的是类似上例中的下标索引方式,那么你必须清楚的了解到,第二次= a[{1,2,3}]所要显示的内容是不存在的。为什么? 因为第二次所使用的下标索引,与table(a)在创建初所使用的内存地址是不一样的,也就是说,第一个{1,2,3}与第二个{1,2,3}只是内容相等的两个不同内存地址的引用。解决办法当然是事先记录好引用地址。 > tablekey = {1,2,3} -- create a table with a variable referencing it > a = { [tablekey]="yadda" } -- construct a table using the table as a key > for k,v in pairs(a) do print(k,v) end -- display the table elements table: 0035F2F0 yadda > = a[tablekey] -- retrieve a value from the table yadda > print(tablekey) -- the table value is the same as the key above table: 0035F2F0 我们暂时将字符串索引键视为一种静态的字面量吧。 > t = { apple=5 } > a = "apple" > b = "apple" > print(t.apple, t[a], t[b]) -- all the same value because there is only one "apple"! 5 5 5 更夸张的索引键是一个函数. > t = { [function(x) print(x) end] = "foo" } > for key,value in pairs(t) do key(value) end foo