iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Software Development

在麥塊的農場裡寫 Lua系列 第 7

Day7 開機學習 Lua - 條件判斷與迴圈控制

上一回分享的是,Lua 標準函式庫
今天想來探索 Lua 條件判斷與迴圈控制,再次回到 CC: Tweaked Computer 的開機訊息程式碼
motd.lua

local date = os.date("*t")
if date.month == 1 and date.day == 1 then
    print("Happy new year!")
elseif date.month == 12 and date.day == 24 then
    print("Merry X-mas!")
elseif date.month == 10 and date.day == 31 then
    print("OOoooOOOoooo! Spooky!")
else
    local tMotd = {}

    for sPath in string.gmatch(settings.get("motd.path"), "[^:]+") do
        if fs.exists(sPath) then
            for sLine in io.lines(sPath) do
                table.insert(tMotd, sLine)
            end
        end
    end

    if #tMotd == 0 then
        print("missingno")
    else
        print(tMotd[math.random(1, #tMotd)])
    end
end

條件判斷 if

我將上述程式碼只擷取條件判斷的部分,結構如下
truefalse 只是我任意給的值
不過,有人看出來,這樣實際上日期是哪一天嗎 XD?

if true and false then
    print("Happy new year!")
elseif false and false then
    print("Merry X-mas!")
elseif false and true then
    print("OOoooOOOoooo! Spooky!")
else
    if false then
        print("missingno")
    else
        print(tMotd[math.random(1, #tMotd)])
    end
end

而除了 and 之外,還可以用 ornot

if false or nil then        -- nil 也是 false
    print(1)
elseif not true then        -- not true = false
    print(2)
elseif 0 or false then      -- 0 是 true !
    print(3)
elseif 123 and false and not 'abc' then   -- 除了 false 和 nil,任何值都是 true
    print(4)
else
    print(5)
end

條件判斷 switch

介紹完 if 之後當然就來介紹 switch ...
.....
不是,Lua 沒有原生支援 switch 語法
但網路上有人分享一些模擬寫法
以鐵人 lagagain 的文章為例
https://ithelp.ithome.com.tw/articles/10243929

option = "one"

switch = {
  ["one"] = function () print "run one" end,
  ["tow"] = function () print "run two" end,
}

switch[option]() -- => run one

迴圈控制 for

for 迴圈的部分,上述的程式碼主要結構如下,有著 foreach 的概念

for sLine in io.lines(sPath) do
    table.insert(tMotd, sLine)
end

也可以明確指定初始值、結束值、遞增值

for i = 1, 10, 1 do -- 初始值、結束值、遞增值
  print(i)
end

如果要中途脫離迴圈,可以用 break,跟其他語言的用法沒什麼不同
但是 Lua 沒有 continue !
這部分就必須自己用邏輯去實了

迴圈控制 while

有了 for 就也要談談 while 了,結構如下

while(condition)
do
   -- statement
end

那麼 do .. while 呢?
Lua 沒有 do .. while,有的是 repeat .. until

repeat
   -- statement
until(condition)

今天的探索就到這裡,下一回我將繼續深入 CC: Tweaked Computer 挖礦!


上一篇
Day6 開機學習 Lua - 標準函式庫
下一篇
Day8 開機學習 Lua - 迴圈控制、迭代函數
系列文
在麥塊的農場裡寫 Lua30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言