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

我制作了一个地板元素的表格:

map.list = {}
--第一个元素
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 = ??? --前一个地板的 x + 前一个地板的宽度
        floor.y = y
        floor.width = width
        floor.height = screenHeight - floor.y
        table.insert(map.list,floor)
        return floor
end

正如你所看到的,这里没有索引。我怎么能访问前一个元素的值?

点赞
用户34799
用户34799

当你使用 table.insert 时,值是具有索引的(Lua 表中的每个值都有索引)。它们被分配给第一个可用的数值索引 - 数组长度加 1。在 Lua 中,# 操作符可用于获取数组风格表的长度:

local list = {}
table.insert(list,'foo') -- 等同于 list[1] = 'foo'
table.insert(list,'bar') -- 等同于 list[2] = 'bar'
table.insert(list,'baz') -- 等同于 list[3] = 'baz'
print(#list) -- 输出 '3'

您可以通过检查表的长度的键来访问数组中的最后一个值,即最后一个值(请记住,Lua 数组传统上从 1 开始):

print(list[#list]) -- 输出 'baz'

因此,要访问先前元素的值,您需要获取列表中的最后一个项目并检查它:

local lastfloor = map.list[#map.list]
-- 假设 floor 在之前的某个地方被定义
floor.x = lastfloor.x + lastfloor.width

琐碎的注释:如果您的表有“洞”(在两个非 nil 值之间的数值索引处的 nil 值),则像“长度”这样的概念会变得模糊。它似乎不会影响此特定用例,但这种情况确实会发生。

2013-09-06 20:14:35