Lua的循环知道什么时候结束循环
有没有在Lua一份声明中说,让我来定它是否是最后一个循环周期? 当我无法确定循环将循环多少时间?Lua的循环知道什么时候结束循环
实施例:
for _, v in pairs(t) do
if I_know_this_is_your_last_cycle then
-- do something
end
这是简化missingno的回答版本::-)
for _, v in pairs(t) do
if next(t,_) == nil then
-- do something in last cycle
end
end
@nuberelo - 在输入“for”循环之前,应该将'function(a,b)'值保存到变量't'。 – 2013-04-08 23:56:13
一般来说,没有。从Lua docs可以看到,for循环在迭代器之上是while循环的语法糖,因此它只知道在循环开始时循环是否结束。
如果你真要查,如果你明确地用while循环进入最后一次迭代,然后我就简单的代码的东西。
local curr_val = initial_value
while curr_val ~= nil then
local next_val = get_next(initial_value)
if next_val ~= nil then
--last iteration
else
--not last iteration
end
curr_val = next_val
end
如果你想的例子与pairs
功能转换,你可以使用next函数作为迭代器。
另外,我会建议在编写像这样的循环之前考虑两次。编码的方式意味着它很容易编写代码,当您迭代0或1个元素或编写不正确处理最后一个元素的代码时,该代码无法正常工作。大多数情况下写一个简单的循环,并在之后放置“结尾”代码,该循环更合理。
有几个方法可以做到这一点。最简单的是只使用标准的for循环,并检查自己,像这样:
local t = {5, nil, 'asdf', {'a'}, nil, 99}
for i=1, #t do
if i == #t then
-- this is the last item.
end
end
或者,你可以滚你自己的迭代函数表,告诉你,当你在最后一个项目,像这样的:
function notifyPairs(t)
local lastItem = false
local i = 0
return
function()
i = i + 1
if i == #t then lastItem = true end;
if (i <= #t) then
return lastItem, t[i]
end
end
end
for IsLastItem, value in notifyPairs(t) do
if IsLastItem then
-- do something with the last item
end
end
代码的第一部分仅适用于从1开始以连续整数索引的表。 – Caladan 2013-04-04 18:42:33
是的,他没有给出他的桌子的例子,所以我假设他正在建造他的桌子,就像我在上面(自动生成的指数)。 – 2013-04-04 18:43:30
你也许可以试着写是这样的:
--count how many elements you have in the table
local element_cnt = 0
for k,v in pairs(t) do
element_cnt = element_cnt + 1
end
local current_item = 1
for k,v in pairs(t)
if current_item == element_count then
print "this is the last element"
end
current_item = current_item + 1
end
或本:
local last_key = nil
for k,v in pairs(t) do
last_key = k
end
for k,v in pairs(t) do
if k == last_key then
--this is the last element
end
end
谢谢大家的帮助!我在你的帮助下为你服务! :) – nuberelo 2013-04-04 21:40:33
你的意思'break'声明?是的,它存在于Lua。 – 2013-04-04 18:21:32
你能举一个更好的例子说明为什么你需要这样做吗?你在做什么是我的代码味道... – hugomg 2013-04-04 18:27:45
不,我知道关于break,但break只是结束循环。对不起,我的例子很糟糕。 为_,V在对(T)做 如果_ == last_cycle_statement然后 - 做一些 结束 我在寻找 “last_cycle_statement” 如果存在的话,当然。 – nuberelo 2013-04-04 18:29:35