请教一个Lua新手问题
书上说lua的table作为数组,其索引最好是以1开始,并有许多机制依赖于此。
请问长度操作符#(返回最后一个元素的索引)是否与这个有关?
请看下面代码:
a = {}
for ia = 5,11 do
a[ia] = ia
end
print('#a=' .. #a)
print('==================')
b = {}
for ib = 5,12 do
b[ib] = ib
end
print('#b=' .. #b)
print('===================')
c = {}
for ic = 4,11 do
c[ic] = ic
end
print('#c=' .. #c)
print('===================')
输出结果
lua
#a=0
==================
#b=0
===================
#c=11
===================
[解决办法]
5.2版本的手册上(http://www.lua.org/manual/5.2/manual.html#3.4.6)明确说明了:
the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some integer n
所以对你举的几个例子, #的返回值是没有明确定义的, 避免这样用就行了。