I've been using the length operator (#) lots these days, since the thread here which showed it was much faster than table.maxn.
However, I've begun using structures which have both tightly-packed enumerated data, and data with string keys. For example:
test = {
x = 0,
y = 0,
name = "Funny Table",
}
for i=1, 100 do
test = i
end
this table would then have 103 pieces of data.
I often want to iterate through the numericly indexed elements of the table, which I could do with i=1, table.maxn(test). The function table.maxn is very clearly "The highest order numerical index" while the description of the length operator is a bit less clear.
Both appear to be working, but the length operator has several warnings about calling it. I can't quite make up my mind whether or not I should be safe and sacrifice some performance now. Anyone have any insight?
--Mr. Strange
picky question about length operator
-
- Party member
- Posts: 101
- Joined: Mon Aug 11, 2008 5:19 am
Re: picky question about length operator
As long as you don't have "holes" (i.e. x[1], x[2], x[3] and x[5] are defined, but x[4] is nil), the length operator should do just fine. My suggestion is not to have holes (in fact, my suggestion would be not to mix numbers and strings in the same table: the table's name should give you a clue about its function, and having one table with two functions means that name will be confusing whichever way you look at it).
Re: picky question about length operator
If i remember correctly the length operator don't count the length but returns a stored length value. If you modify a list with table.insert & co it gets updated. So the length operator should work as long as you don not manually set entries like l["lala"] = 1 or l[40] = 1.
But you can always iterate over all elements and count them like "for k,v in pairs(l) do i = i +1 end" (dont know if maxn does this) but its slower than the length operator.
But you can always iterate over all elements and count them like "for k,v in pairs(l) do i = i +1 end" (dont know if maxn does this) but its slower than the length operator.
-
- Party member
- Posts: 101
- Joined: Mon Aug 11, 2008 5:19 am
Re: picky question about length operator
maxn does indeed iterate in just that fashion, which makes it appropriate but slow.hagish wrote:If i remember correctly the length operator don't count the length but returns a stored length value. If you modify a list with table.insert & co it gets updated. So the length operator should work as long as you don not manually set entries like l["lala"] = 1 or l[40] = 1.
But you can always iterate over all elements and count them like "for k,v in pairs(l) do i = i +1 end" (dont know if maxn does this) but its slower than the length operator.
You've convinced me that I'm safe using the length operator. Thanks.
--Mr. Strange
Who is online
Users browsing this forum: Ahrefs [Bot] and 2 guests