[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: hpairs?
- From: Steve Litt <slitt@...>
- Date: Tue, 28 Dec 2010 15:57:02 -0500
On Tuesday 28 December 2010 14:45:04 Richard Hundt wrote:
> On 12/28/2010 09:25 AM, Dirk Laurie wrote:
> > How does one iterate over all the keys of a table _except_
> > the ones that ipairs would reach?
> >
> > Unsuccessful attempts so far:
> >
> > for k,v in pairs(t) do if not tonumber(k) then ...
> >
> > for k,v in pairs(t) do if type(k)!='number' then ...
> >
> > for k,v in pairs(t) do if type(k)!=number or k>#t then ...
> >
> > for k,v in hpairs(t) do ...
> >
> > Dirk
>
> Is there something inherently Bad about doing this?
>
> for k,v in next, t, #t > 0 and #t or nil do
> ...
> end
>
> I use this for a JSON serializer to encode the hash part, and it seems
> to work, but that may be implementation specific and not reliable (i.e.
> it relies on next() returning the first key in the hash part when given
> the last key in the array part). Critique?
>
> Cheers,
> Richard
I just placed your algorithm in my test program, and yours produced the same
results as mine, and the same results as one would expect. I don't even
understand yours, but it appears to work perfectly. See below:
#!/usr/bin/lua
local arr={"one", "two", "three"}
arr[4] = "four"
arr[1.5] = "one point five"
arr["steve"] = "Litt"
print("Richards")
for k,v in next, arr, #arr > 0 and #arr or nil do
print(k)
print(v)
print("")
end
print("Mine")
for k, v in pairs(arr) do
if type(k) ~= "number" or math.ceil(k) ~= k then
print(k)
print(v)
print("")
end
end
SteveT
Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt