• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

lua中 table.getn(t) 、#t、 table.maxn(t) 这三个什么区别?

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
RT
local t = {1,888,x= 999,b=2,5,nil,6,7,[10]=1,8,{z = 1,y = 1},nil,nil}

print(table.getn(t))
print(#t)
print(table.maxn(t))

输出:8 8 8
------------如果把[10] =1 改成[11] =1 那么输出8 8 11 这又是为什么?
 
 
 
1个回答
 
maxn lua 5.2 已经抛弃了,不过依然可以使用。
更多追问追答
 
 
追问
但是它计算的是数组元素。不包括hash 键值。
而且数组是以第一个nil元素来判断数组结束。

=========这个意思不就是说get(n)只会计算到第一个nil就停止么,但是我上面的例子好像没有停止,
 
追答
a={1,3,a='b',[6]='six',['10']='ten'}
a 和 [6] ['10']是作为hash保存的。#a => 2 他是不包括hash成员的计数。
这句话我说的有点误会。其实数组的数据结构也是hash。lua中数组的意思是:table的元素拥有连续的数字索引。比如:{[1]=1,[2]=2,[3]=3}

The length operator is denoted by the unary prefix operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
A program can modify the behavior of the length operator for any value but strings through the __len metamethod (see §2.4).
Unless a __len metamethod is given, 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. In that case, n is its length. Note that a table like
{10, 20, nil, 40}
is not a sequence, because it has the key 4 but does not have the key 3. (So, there is no n such that the set {1..n} is equal to the set of positive numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence.
上面这句话是手册里的内容。
table的长度是 table为序列时的某个n 使得,{1..n} == table的所有数字索引。也就是说序列的数字索引必须连续。
# 运算得到的length 只针对 序列有意义 。当table不是序列时length 没有明确含义。
table中间包括nil,这个table就不是序列,例如:
a={10, 20, nil, 40}

它不是序列,因为他的数字索引是 1 2 4 不是连续的,所以它不是序列。
所以 #a 得到的值并不能准确反映table的元素个数。
手册的意思是说 针对非序列使用#,而那个table又没有__len 时它值无意义的。

再给你个实例:
a={1,2,3,4,5}
print(#a)
5
a[2]=nil
print(#a) --此时a已经不是序列,此时对数列使用# , 具体意义不明。
5
a[5]=nil --删除最后元素
print(#a) --看看 结果。
1
===
对于你想删除某个序列的元素,必须使用 table.remove 而不是 a[n]=nil

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
(三)Lua脚本语言入门发布时间:2022-07-22
下一篇:
redis与Lua整合以及使用lua实现秒杀功能发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap