Lua 在没有索引的情况下访问表中的上一个元素

Lua 在没有索引的情况下访问表中的上一个元素,lua,lua-table,Lua,Lua Table,我制作了一张地板元素表: map.list = {} --first element firstfloor = {} firstfloor.x = 50 firstfloor.y = 800 firstfloor.width = 500 firstfloor.height = screenHeight - firstfloor.y table insert(map.list,firstfloor) 现在我需要为下一层做一个构造器。“x”值只是上一层的“x”位置+宽度 function map:

我制作了一张地板元素表:

map.list = {}
--first element
firstfloor = {}
firstfloor.x = 50
firstfloor.y = 800
firstfloor.width = 500
firstfloor.height = screenHeight - firstfloor.y
table insert(map.list,firstfloor)
现在我需要为下一层做一个构造器。“x”值只是上一层的“x”位置+宽度

function map:newFloor(x,y,width)
        local floor = {}
        floor.x = ??? --previous floor's x + previous floor's width
        floor.y = y
        floor.width = width
        floor.height = screenHeight - floor.y
        table.insert(map.list,floor)
        return floor
end

正如你所看到的,这里没有索引。如何访问上一个元素的值?

使用
表。插入时,值确实有索引(Lua表中的每个值都有索引)。它们被分配到第一个可用的数字索引-数组长度加1。在Lua中,
#
运算符给出数组样式表的长度:

local list = {}
table.insert(list,'foo') -- equivalent to list[1] = 'foo'
table.insert(list,'bar') -- equivalent to list[2] = 'bar'
table.insert(list,'baz') -- equivalent to list[3] = 'baz'
print(#list) -- prints '3'
您可以通过检查表长度处的键来访问数组中的最后一个值,即最后一个值(请记住,Lua数组通常从1开始):

因此,要访问上一个元素的值,请获取列表中的最后一项并检查:

local lastfloor = map.list[#map.list]
-- assuming floor is defined somewhere above
floor.x = lastfloor.x + lastfloor.width

迂腐的注释:如果您的表有“洞”(
nil
值位于两个非
nil
值之间的数值索引),那么“长度”之类的概念就会变得模糊。看起来这不会影响这个特定的用例,但它会出现。

您可以通过
map.list[#map.list]
local lastfloor = map.list[#map.list]
-- assuming floor is defined somewhere above
floor.x = lastfloor.x + lastfloor.width