[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua, LuaJIT2 and differences with the length operator
- From: Duncan Cross <duncan.cross@...>
- Date: Wed, 29 Dec 2010 15:39:28 +0000
On Wed, Dec 29, 2010 at 3:18 PM, Daniele Alessandri
<suppakilla@gmail.com> wrote:
> Hi everyone,
>
> I just noticed a subtle difference between using the length operator
> on tables containing nil values on Lua and LuaJIT2 and I would like to
> get a clarification:
>
> Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
>> t = { 'foo', nil, 'bar' }
>> print(#t)
> 3
>
> LuaJIT 2.0.0-beta5 -- Copyright (C) 2005-2010 Mike Pall. http://luajit.org/
> JIT: OFF CMOV SSE2 SSE4.1 fold cse dce fwd dse narrow loop abc fuse
>> t = { 'foo', nil, 'bar' }
>> print(#t)
> 1
>
> Which one is right? I guess Lua, even if
> http://www.lua.org/manual/5.1/manual.html#2.5.5 states that "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).".
>
> I would expect at least the same behavior, or am I just doing it wrong
> by trying to rely on the current one showed by Lua 5.1?
You are doing it wrong by trying to rely on that. As the manual
states, "#t can be any of the indices" - *any* of them, it is
deliberately undefined which. You should treat it as if it is random,
even though it may seem to be consistent.
In fact, it is not even consistent in Lua 5.1. For example, these two
ways of populating a table should get us identical tables but they get
different length results (at least, they do for me, it might even vary
from machine to machine):
> t1 = { 'foo', nil, 'bar' }
> print(#t1)
3
> t2 = {}
> t2[1] = 'foo'
> t2[2] = nil
> t2[3] = 'bar'
> print(#t2)
1
-Duncan