我制作了一张地板元素表:
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
如您所见,此处没有索引。我如何访问前一个元素的值?
最佳答案
当您使用table.insert
时,值确实 有索引(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 开始):
print(list[#list]) -- prints 'baz'
因此,要访问前一个元素的值,您需要获取列表中的最后一项并检查:
local lastfloor = map.list[#map.list]
-- assuming floor is defined somewhere above
floor.x = lastfloor.x + lastfloor.width
迂腐的注解:如果您的表格有“漏洞”(nil
值位于两个非 nil
值之间的数字索引处),则“长度”等概念会变得模糊。看起来这不会影响这个特定的用例,但它会出现。
关于lua - 访问没有索引的表中的前一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18665413/