您的位置:首页 > 编程语言 > Lua

关于lua table.getn()和#

2016-06-13 14:47 741 查看
在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
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更简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua