2013-04-04 152 views
1

有沒有在Lua一份聲明中說,讓我來定它是否是最後一個循環週期? 當我無法確定循環將循環多少時間?Lua的循環知道什麼時候結束循環

實施例:

for _, v in pairs(t) do 
if I_know_this_is_your_last_cycle then 
-- do something 
end 
+0

你的意思'break'聲明?是的,它存在於Lua。 – 2013-04-04 18:21:32

+0

你能舉一個更好的例子說明爲什麼你需要這樣做嗎?你在做什麼是我的代碼味道... – hugomg 2013-04-04 18:27:45

+0

不,我知道關於break,但break只是結束循環。對不起,我的例子很糟糕。 爲_,V在對(T)做 如果_ == last_cycle_statement然後 - 做一些 結束 我在尋找 「last_cycle_statement」 如果存在的話,當然。 – nuberelo 2013-04-04 18:29:35

回答

4

這是簡化missingno的回答版本::-)

for _, v in pairs(t) do 
    if next(t,_) == nil then 
    -- do something in last cycle 
    end 
end 
+0

@nuberelo - 在輸入「for」循環之前,應該將'function(a,b)'值保存到變量't'。 – 2013-04-08 23:56:13

1

一般來說,沒有。從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個元素或編寫不正確處理最後一個元素的代碼時,該代碼無法正常工作。大多數情況下寫一個簡單的循環,並在之後放置「結尾」代碼,該循環更合理。

0

有幾個方法可以做到這一點。最簡單的是隻使用標準的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

代碼的第一部分僅適用於從1開始以連續整數索引的表。 – Caladan 2013-04-04 18:42:33

+0

是的,他沒有給出他的桌子的例子,所以我假設他正在建造他的桌子,就像我在上面(自動生成的指數)。 – 2013-04-04 18:43:30

1

你也許可以試着寫是這樣的:

--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 
+0

謝謝大家的幫助!我在你的幫助下爲你服務! :) – nuberelo 2013-04-04 21:40:33