tags:

views:

73

answers:

1

Why are there only 4 fields in this lua table? Shouldn't there be 7?

   polyline = {color="blue", thickness=2, npoints=4,
                 {x=0,   y=0},
                 {x=10, y=0},
                 {x=-10, y=1},
                 {x=0,   y=1}
               }

print(table.maxn(polyline))    -- returns 4. Why?
print(polyline[2].x)   -- returns 10. Why? 

I thought polyline[2] would index to "thickness", which is the 2nd field in this table.

+5  A: 

Maybe you should reread the table constructor operator manual. To summarize, the named fields in the table (i.e. color, thickness, npoints) don't have any numerical index assigned, just the name. If you omit the name, an 1-based index is generated. Your definition of polyline is equivalent to this one:

   polyline = {
                 color="blue", thickness=2, npoints=4,
                 [1] = {x=0,   y=0},
                 [2] = {x=10, y=0},
                 [3] = {x=-10, y=1},
                 [4] = {x=0,   y=1}
               }

This explains the output of print(polyline[2].x) (also, table fields in Lua tables don't have any ordering; pairs is allowed to enumerate them in any order). As for table.maxn:

[table.maxn] Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)

So the output is again, correct. The table really contains 7 fields, but table.maxn doesn't return the total number of fields at all.

Seriously, rtfm...

sbk