iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
Software Development

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

Day6 開機學習 Lua - 標準函式庫

Day6 開機學習 Lua - 標準函式庫

上一回分享的是,Lua 變數型別與宣告
今天主題則是 Lua 內建的標準函式庫,先看上次相同的程式碼:
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

在這裡所看到的,os, string, io, table, math 都是內建的標準函式庫,此外還有 coroutine, package, utf8, debug
而事實上,我一直使用的 print(), tonumber(), tostring(), type() 則都是屬於 Basic 函式庫
以下會針對上述用到的函數做簡介

日期與時間: os.date(), os.time()

os.date("*t") 是回傳一個 table 變數,有 year、month、day 等屬性可供操作
如果沒有給 *t 參數,預設是回傳當前日期時間的字串表示
os.time() 則是回傳 timestamp
其他 os function 可參考官方文件

var = os.date("*t")
print(type(var))  -- table
print(var)        -- table: 0x2188870
var = os.date()
print(type(var))  -- string
print(var)        -- Tue Sep 14 04:25:20 2021
var = os.time()
print(type(var))  -- number
print(var)        -- 1631589920

檔案逐行讀取: io.lines()

io 用來處理檔案的存取
io.lines 是讀取檔案後,回傳 iterator 函數,以便可以在迴圈中逐一讀取每一行資料
其他 function 可參考 Lua io 官方文件

table 變數操作: table.insert()

table.insert 的語法結構是

table.insert(list, [pos,] value)

預設行為是將 value 存入 list 的最後一筆
中間 pos 是 index,但注意從 1 開始,跟其他語言從 0 開始不同,可省略
其他 function 可參考 Lua table 官方文件

數學運算隨機數:math.random()

math.random() 則回傳 0~1 的隨機數,範圍是 [0,1)
和其他語言比較不同的是
math.random(5) 等同於 math.random(1, 5),只回傳 1, 2, 3, 4, 5 任何一個整數
其他 math function 可參考 Lua math 官方文件

字串處理:string.gmatch()

gmatch() 會以規則運算式來比對字串,並回傳 iterator 函數,來取得每次符合的子字串
以下程式碼就是將除了冒號以外的字串找出來

string.gmatch(settings.get("motd.path"), "[^:]+")

關於可運用的規則運算式,可參考 Lua regular expression pattern

其他 string function 可參考 Lua string 官方文件

再次研究開機程式

那我有個問題,為什麼是冒號?不是分號、逗號或其它字元呢?
我再次用 motd.path 去搜尋 rom/ 所有程式碼
找到 bios.lua 有這麼一段

settings.define("motd.path", {
    default = "/rom/motd.txt:/motd.txt",
    description = [[The path to load random messages from. Should be a colon (":") separated string of file paths.]],
    type = "string",
})

看起來,電腦預設行為是從 /rom/motd.txt/motd.txt 隨機找一行來顯示開機訊息
你只要先清除之前的 motd.path 環境變數
在麥塊電腦底下輸入

set motd.path nil

然後編輯 /motd.txt 內容後多次重新開機,就可以印證。

以上是今天的分享,下次我會探索這段 Code 最後一部分
條件判斷與迴圈控制


上一篇
Day5 「開機」學習 Lua - 變數型別與宣告
下一篇
Day7 開機學習 Lua - 條件判斷與迴圈控制
系列文
在麥塊的農場裡寫 Lua30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言