iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0
Software Development

30天 Lua重拾筆記系列 第 14

【30天Lua重拾筆記14】基礎2: 控制-while、repeat迴圈

本文同步發表於個人網站

print("鐵人賽開始")

for day=1,30,1 do
  print("第" .. day .. "天: 每天寫文章")
end

print("鐵人賽結束")

for迴圈適合用於次數明確的情況。例如鐵人賽30天發文不間斷,每天發一篇,發完30完賽。向這樣知道進步條件(每天一篇),中止條件(30篇),就非常適合用 for 迴圈。

Repeat/until迴圈

但有時候只知道中止條件,過程並不確定。像是在第n天,就寫n篇文章來囤稿,對我而言會是幾天完賽呢?

print("鐵人賽開始")
day = 1 -- 第幾天
completed = 0 -- 完成篇數

repeat
  completed = completed + day
  print("第" .. day .. "天: 每天寫文章,完成"..completed.."篇")
  day = day + 1
until completed > 30

print("鐵人賽結束,完成篇數:"..completed)  -- Output: 鐵人賽結束,完成篇數:36  -- (1+8)*8/2

鐵人賽開始
第1天: 每天寫文章,完成1篇
第2天: 每天寫文章,完成3篇
第3天: 每天寫文章,完成6篇
第4天: 每天寫文章,完成10篇
第5天: 每天寫文章,完成15篇
第6天: 每天寫文章,完成21篇
第7天: 每天寫文章,完成28篇
第8天: 每天寫文章,完成36篇
鐵人賽結束,完成篇數:36

需要每天寫文章,直到累積的文章超過30篇,也就完賽了。如果在第n天寫n篇,也只需要8天就完賽。

While迴圈

如果需要跑到一個為10的點。而當前位置不會超過該點,每次可以往該點接近1,嘗試列出接近的過程:

destination = 10  -- 終點位置
current_pos = 0  -- 目前位置

print([[馬拉松賽跑
============]])

print("終點位於:"..destination)
print("目前在:"..current_pos)

while current_pos < destination do
  current_pos = current_pos + 1
  print("往前跑1㎞,目前位於"..current_pos)
end

print("抵達終點,目前位於"..current_pos)

馬拉松賽跑

終點位於:10
目前在:0
往前跑1㎞,目前位於1
往前跑1㎞,目前位於2
往前跑1㎞,目前位於3
往前跑1㎞,目前位於4
往前跑1㎞,目前位於5
往前跑1㎞,目前位於6
往前跑1㎞,目前位於7
往前跑1㎞,目前位於8
往前跑1㎞,目前位於9
往前跑1㎞,目前位於10
抵達終點,目前位於10

小節

在C/C++語言裡有whiledo-while。就一般來說,如果是需要先判斷在執行使用while,需要先執行在判斷do-while。類似的,Lua提供whilerepeat-until,使用更語意化的寫法。

兩者通常可以轉換。使用何者我認為更取決於怎樣寫更接近自己思考的方式。


上一篇
【30天Lua重拾筆記13】基礎2: 控制-for迴圈
下一篇
【30天Lua重拾筆記15】基礎2: Label and Goto
系列文
30天 Lua重拾筆記36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言