Lua 复杂 Tables/List 大小

Lua Complex Tables/List Sizes

我正在尝试查找 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

我希望条目 test[0].xtest[0].ytable.getn(test[0]) 为 2,但结果为 0。这是为什么,我需要做什么才能得到我想要的我在找什么?

请注意,Lua 5.0 中的 table.getn 自 Lua 5.1

以来已被 # 运算符取代

table 的大小仅对 table 的序列部分有效(即,从 1 到某个数字 n 的正数字键, n 是尺寸)。

在此示例中,test[0] 只有两个 kesy "x""y"。结果它的大小是 0.

table.getn and the lua 5.1 length operator 定义为对 "lists" 或数组进行操作。你的 table 不是一个。它没有数字索引。

所以结果在 lua 5.1 中是未定义的(尽管这里是零),在 lua 5.0 中是 0 因为大小被定义为 one less the first integer index with a nil value 这是整数指数 1.

另外值得注意的是 table.getn(test[0].x) 将 return 2table.getn(test[0].y) 将 return 0 (因为 lua数组从 1).

开始