Hi, I was working with tables and OOP, and I found some unexpected outputs with object lengths.
local object = {
'bean',
[5]='Bean2',
['String bean']='Beans'
}
local object2 = {
'bean',
[3]='Bean2',
}
local object3 = {
'bean',
['string bean'] = 'bean'
}
local object4 = {
'bean',
[3] = 'bean',
['string bean'] = 'bean'
}
print(#object)
print(#object2)
print(#object3)
print(#object4)
All four of these output 1.
A workaround for this would be to use something like this;
function getTableLength(tab)
local totalLength = 0
for _ in next, tab do
totalLength = totalLength+1
end
return totalLength
end
Hello.
Here the explanation to why it gives “0” as output:
Table elements with non-numerical keys (Dictionarys) won’t count towards the length of the table when using either the # operator or the table.getn function.
The tables in your code have elements with non-numerical keys, thus the output: 0.