The size of an array

Just as you are able to find the length of a string with the # operator, you can find the length of an array as well. This is because the # operator gives back the size of a table. We can use this operator to loop through an array that has a dynamic size, for example, such as the following code snippet:

arr = { "a", "b", "c", "d", "e", "f", "g" }

length = #arr
print ("array length: " .. length)

for i=1,#arr do
print (arr[i])
end

The length operator # will only count array elements starting from index 1. This means if you use index 0, it will not be counted towards the number of elements in the array:

arr = { }

arr[0] = "x" -- not counted towards length
arr[1] = "y"
arr[2] = "z"

length = #arr -- length = 2!
print ("array length: " .. length)

Trying to find the length of a sparse array is tricky. The # considers an array over if it finds two nil values one after the other. For example, in this code, the length of the array is incorrectly reported as 2:

arr = { }

arr[1] = "x"
arr[2] = "y"
-- Skipping 3 & 4, at least 2 nils after each other end the array
arr[5] = "z" -- not counted towards length
arr[6] = "w" -- not counted towards length

length = #arr -- length = 2, which is WRONG!
print ("array length: " .. length)

Because of this unintuitive behavior, using the # operator to find the length of an array is considered to be unreliable. A better way of finding the length of an array will be covered later in this chapter, in the Iterating section.

The behavior of the length operator is documented in the Lua 5.2 manual under section 3.4.6 - The Length Operator, found online at https://www.lua.org/manual/5.2/manual.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.181