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 挖矿!


<<:  Day 07 - Transduce I

>>:  【Day22】判断计数器数字初始值是否为0且按下增加的按钮时结果是否正确 「(°ヘ°)

33岁转职者的前端笔记-DAY 2 如何处理 BUG 及遇到 BUG 的心态

相信很多程序开发者在开发专案的时候一定会遇到同样的问题 那就是一定会碰到有 BUG 时候 在遇到 B...

AWS资料仓储

当有大量资料需要分析处理时, AWS也提供了云端资料仓储分析Redshift. 在 Redshift...

[Day 12] 简单的单元测试实作(六)

其实到目前为止, 我们所做的动作都差不多, 只是差在逻辑上的判断而已, 相信大家已经觉得有点拖屏了,...

【後转前要多久】# Day20 BootStrap - 通用类别 Utilities

今天要来介绍 Bootstrap 工具、通用类别 在这章节中,最重要的就是要熟悉各种装置尺寸代号, ...

AZ-304 Practice Exam - The key to Transform Failure into Success

Azure Solutions Architect Expert AZ-304 certificat...