关于lua table.getn()和#

在lua中table是强大的数据组合类型,但是因为强大所以有些地方使用会不好理解。
table可以是list:local list_table = {1, 2, 3}
table可以是dict:local dict_table = {a=1,b=2}
table可以是链表:local lb_tale={value = 1, next=nil}
当然table也可以混合。

lua5.0之后版本table.getn()被废弃,可使用#.

但是有个问题是在获取table的长度的时候:

2.5.5 - The Length Operator
The length operator is denoted by the unary 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).
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has “holes” (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

所以在有需要获取长度的table中尽量不要使用混合table,并且不要设置nil。如果你设置nil,你需要手动去修改table的长度table.setn()

虽然我们可以通过设置某个元素为nil来达到删除这个元素的目的,但是直接进行设置会带来获取长度的问题,可以使用table.remove(index)来删除,但是这个方法还是有很多局限的。
如果想避免遇到莫名的麻烦,尽量让你的table更简单。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值