In filters accessing the last item in a list is fairly common. The standard way to do it in Lua is to do list[#list], but it very quickly becomes unworkable when there are deeply nested lists. The filter ends up with monstrosities like blocks[#blocks].content[#blocks[#blocks].content] where the same identifiers are repeated multiple times, which hurts readability and increases the risk of introducing bugs. An alternative is to litter the code with intermediate variables, e.g. local content = blocks[#blocks].content and then content[#content].
The solution
The perfect solution would be for List to introduce a helper function List:last, which would return the last item or nil if the list is empty. The above example could be then expressed as blocks:last().content:last(), which is simple and elegant.
A more elastic approach would be to add List:get which would accept negative indexes, similarly to other languages but unlike Lua tables indexing. The above example could then be expressed as blocks:get(-1).content:get(-1).
The problem
In filters accessing the last item in a list is fairly common. The standard way to do it in Lua is to do
list[#list]
, but it very quickly becomes unworkable when there are deeply nested lists. The filter ends up with monstrosities likeblocks[#blocks].content[#blocks[#blocks].content]
where the same identifiers are repeated multiple times, which hurts readability and increases the risk of introducing bugs. An alternative is to litter the code with intermediate variables, e.g.local content = blocks[#blocks].content
and thencontent[#content]
.The solution
The perfect solution would be for
List
to introduce a helper functionList:last
, which would return the last item ornil
if the list is empty. The above example could be then expressed asblocks:last().content:last()
, which is simple and elegant.A more elastic approach would be to add
List:get
which would accept negative indexes, similarly to other languages but unlike Lua tables indexing. The above example could then be expressed asblocks:get(-1).content:get(-1)
.