lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dirks question was how to get all keys that do not show up on ipairs()
for {1, 2, nil, nil, 5}
this is 5.

On Mon, Jan 3, 2011 at 12:40 AM, Emmanuel Oga <emmanueloga@gmail.com> wrote:
> --------------------------------------------------------------
> EmmanuelOga.com - Software Developer
>
>
>
> On Sun, Jan 2, 2011 at 8:25 PM, Axel Kittenberger <axkibe@gmail.com> wrote:
>> Try it with {1, 2, nil, nil, 5}.
>>
>> will 5 turn up in the not ipairs part?
>
> It won't, but since ipairs stops iterating when it finds the first
> nil, the at_ipairs function will stop there too:
>
> a = arrayTable{1, 2, nil, nil, 5}
>
> for i, v in at_ipairs(a) do
>  print(v) --> prints 1 \n 2
> end
>
> for i, v in at_pairs(a) do
>  print(i, v)  --> does not print anything, all keys are integers
> end
>
> print(a[1]) --> 1
> print(a[2]) --> 2
> print(a[3]) --> nil
> print(a[4]) --> nil
> print(a[5]) --> 5
>
>>
>> On Mon, Jan 3, 2011 at 12:00 AM, Emmanuel Oga <emmanueloga@gmail.com> wrote:
>>> I came up with this experiment involving __index and __newindex to
>>> segregate a table in its array part and non-array part:
>>>
>>> https://gist.github.com/762890
>>>
>>> Caveats:
>>>
>>> It requires an special constructor to create the table:
>>>
>>>  t = arrayTable{1, 2, a = 1}
>>>  t[1.5]=1.5
>>>
>>> It requires special iterators replacing both ipairs and pairs:
>>>
>>>  for k,v in at_ipairs(t) do print(k, v) end
>>>  for k,v in at_pairs(t) do print(k, v) end
>>>
>>> Alternatively you can use the indexes to the real table/array provided
>>> in the table
>>>
>>>  for k,v in ipairs(t.___array) do print(k, v) end
>>>  for k,v in pairs(t.___table) do print(k, v) end
>>>
>>> Which I believe is even more ugly than using the iterators above.
>>>
>>> I tried to override __len on the metatable but apparently that does
>>> not work in lua 5.1 (I read somewhere __len will be overridable for
>>> tables/strings in 5.2?)
>>>
>>> --------------------------------------------------------------
>>> EmmanuelOga.com - Software Developer
>>>
>>>
>>
>>
>
>