[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: pairs(t, skey) and ipairs(t, skey)
- From: Sean Conner <sean@...>
- Date: Wed, 2 Oct 2013 16:53:58 -0400
It was thus said that the Great Tim Hill once stated:
>
> On Oct 2, 2013, at 9:57 AM, Sean Conner <sean@conman.org> wrote:
>
> > Is a sequence of 0 elements valid?
> >
> > So, what exactly is wrong with:
> >
> > sum = 0
> > for i = 1 , #t do
> > sum = sum + t[i]
> > end
> >
> > I mean, besides not checking if each element is a number and not NaN (but
> > then again, you can't check for NaN because NaN ~= NaN and there goes your
> > entire calculation out the window ... )
>
> In my application it is desirable/necessary for me to check that a table
> is indeed a sequence before further processing it. Lua does not provide
> any easy or efficient means of doing so. To me this is a flaw in the
> language. I believe it is easy to fix, but such discussions are frowned
> upon in this list, so I will not discuss this further.
Okay, so what's wrong with this?
function aSum(t)
local sequence = false
local sum = 0
for i = 1 , #t do
if type(t[i]) ~= 'number' then
return false,0
end
sum = sum + t[i]
sequence = true
end
return sequence,sum
end
If the table has no sequence, or if any of the array portion is not a
number, then this returns "false,0", otherwise, it returns "true" and the
sum of the sequence. Now, if you are concerned about holes in the sequence,
even *IF* Lua supported nils (such that { 1 , 2 , nil , 4 , 5 } has a
length of 5) could you consider that a valid sequence to sum? What if the
sequence is { 1 , 2 , nan , 4 , 5 }? nan is a number, but once used in an
expression, the results will be nan (even "x = 0/0 if x == x then print "yes"
end" fails to print an answer).
Now, I'm harping on the sum example because that's the example you
presented. It could very well be the case that the sequence { 1 , 2 , nil ,
4 , 5 } is a valid case, but Lua doesn't handle that, it's stated as such,
so there isn't much you can do there anyway.
While I don't doubt you need to check for sequences, what exactly are you
trying to do with the sequences? I only ask because for anything you are
trying to do, there exists a pathological case (just a reminder, the only
keys that aren't valid are nil and nan).
-spc
- References:
- Re: pairs(t, skey) and ipairs(t, skey), Dirk Laurie
- Re: pairs(t, skey) and ipairs(t, skey), Paul K
- Re: pairs(t, skey) and ipairs(t, skey), Luiz Henrique de Figueiredo
- Re: pairs(t, skey) and ipairs(t, skey), Tim Hill
- Re: pairs(t, skey) and ipairs(t, skey), Luiz Henrique de Figueiredo
- Re: pairs(t, skey) and ipairs(t, skey), Tim Hill
- Re: pairs(t, skey) and ipairs(t, skey), Sean Conner
- Re: pairs(t, skey) and ipairs(t, skey), Tim Hill