2

I am new to lua and my lua version is 5.1.
I've got this problem. Can anybody help me to explain '#'?

local tblTest =  
{  
    [1] = 2,  
    [2] = 5,  
    [5] = 10,  
}  
print(#tblTest)

this output 2 and ..

local tblTest =  
{  
    [1] = 2,  
    [2] = 5,  
    [4] = 10,  
}  
print(#tblTest)

output is 4. Why?
thanks all of u.

Ulf Gjerdingen
  • 1,414
  • 3
  • 16
  • 20
易国锋
  • 45
  • 1
  • 1
  • 4

1 Answers1

3

The output is 4 because the last key with a value is 4 but that doesn't mean that 3 isn't also defined. In lua 3 would be defined as nil. So when you use the # operator it counts every key in a sequence with a value until the last non-nil value. Except,(and I could be wrong about this) the last key in the table is a power of 2, which do to language optimization, it counts up to the value that is a power of 2. In general you should stay away from tables with nil values as there are some other weird behaviors that happen because of this.

This chunk with do what you want though:

local T = {
[1] = 2,
[2] = 5,
[10] = 10
}

local lengthNum = 0

For k, v in pairs(T) do -- for every key in the table with a corresponding non-nil value 
   lengthNum = lengthNum + 1
end
print(lengthNum)
}

What this does is it checks the entire table for keys (such as [1] or [2]) and checks if they have value. Every key with a non-nil value runs the for loop one more time. There might be a shorter way to this, but this is how I would do it.

Jacques
  • 75
  • 10
  • Yes, you are fatally wrong. See the dupe. – Deduplicator Jul 30 '16 at 17:20
  • Is I where I said it counts up to the value with the power of 2, because it should say key for value there, or am I wrong else where? – Jacques Jul 30 '16 at 17:35
  • 1
    It *can* count up to a power of 2 despite earlier holes, though it might not. No guarantee, the details are in the dupe. – Deduplicator Jul 30 '16 at 17:43
  • 1
    And if it happens to run on an implementation using a power-of-2 table for optimization, the allocation-pattern is right, and so on. Nothing to rely on, ever. – Deduplicator Jul 30 '16 at 17:45
  • 1
    @Deduplicator Oh, see! It only does the power of two thing if the last power of 2 has already had memory allocated, right? So, t= {[1] = 1, [2] =2, [4] = 4, [8] = 8 } print (#t) --returns 8 but, t= { [1] = 1, [2] =2, [4] = 4, [16] = 8 } print (#t) --returns 4 – Jacques Jul 30 '16 at 17:50