Lono
Lono

Reputation: 33

Lua Complex Tables/List Sizes

I am trying to find the number of entries for test[0]

test = {}
test[0] = {}
test[0].x = {}
test[0].x[0] = 1
test[0].x[1] = 1
test[0].x[2] = 1
test[0].y = {}
test[0].y[0] = 1

I am expecting table.getn(test[0]) to be 2 for entries test[0].x and test[0].y but it results in 0. Why is this, and what do I need to do to get what I am looking for?

Upvotes: 1

Views: 459

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80921

table.getn and the lua 5.1 length operator are defined to operate on "lists" or arrays. Your table isn't one. It has no numerical indices.

So the result is undefined in lua 5.1 (though it will be zero here) and 0 in lua 5.0 as the size is defined to be one less the first integer index with a nil value which is the integer index 1.

Also worth noting is that table.getn(test[0].x) will return 2 and table.getn(test[0].y) will return 0 (since lua arrays start at 1).

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

Note that table.getn in Lua 5.0 has been replaced by the # operator since Lua 5.1

The size of a table is only valid for the sequence part of a table (i.e, with positive numeric keys from 1 to some number n, and n is the size).

In this example, test[0] has only two kesy "x" and "y". As a result its size is 0.

Upvotes: 2

Related Questions