lua #操作符的作用

在lua中,#一般是用于获取表的长度,即#tableTest就是tableTest的长度了。

但这只是在一般的情况下,如果这个表结构并不是按数字1~N顺序递增的,那么#tableTest获取出来的就有可能是一些奇怪的值。

比如tableTest = { 1, 2, 3, 4 },其#tableTest获取的值就是4。

在之后对tableTest操作:tableTest[10] = 1,#tableTest获取到的仍为4。但这并不是一定的,也有可能是10。具体解释可看官方文档中对其的描述:Lua 5.1 Reference

其中这一段

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).

在下标为数字且从1开始连续的话,其返回的值固定为表长度。而当数组下标中存在不连续的漏洞时(就像上面的下标1,2,3,4,10),其返回的下标就有可能是任何一个实际存在且后一位是nil的下标,在这里有可能是4或10。另外如果下标1为空时,也有可能返回0。

另外关于遍历数组,像以下的这种写法:

for i = 1, #tableTest do
	.....
end

若tableTest在循环过程中存在长度调整,其for循环次数是不受影响的。如果想要实现类似于广度搜索一样的效果,则应该使用以下这种写法:

for key,value in pairs(tableTest) do
	.....
end

这样在向后扫描的时候,新增的数据添加在数组尾部,可以被for in pairs获取到,搜索得以持续进行。(根据实际观察,对于数字类型的下标,for in pairs循环的扫描应该是从小到大进行的)。

猜你喜欢

转载自blog.csdn.net/Vis_Stu/article/details/80811125
今日推荐