上一回我学到的是 Lua 的条件判断与回圈控制
今天我来看最後一段未解的程序码
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
目前只剩下 settings
和 fs
不知怎麽来的?
可以确定的是,他们不是 Lua 内建函式库
一番搜查之下,我在 bios.lua #783 找到这一段
-- Load APIs
local bAPIError = false
local tApis = fs.list("rom/apis")
for _, sFile in ipairs(tApis) do
if string.sub(sFile, 1, 1) ~= "." then
local sPath = fs.combine("rom/apis", sFile)
if not fs.isDir(sPath) then
if not os.loadAPI(sPath) then
bAPIError = true
end
end
end
end
显然的,他是从 rom/apis 取出所有档案後,逐一载入
因为有包含了 rom/apis/settings.lua
所以可以直接使用 settings 来读取或设定环境变数
ipairs
也是 Lua 基础函式库提供的 function,可迭代 table 中每个数值
每次迭代都会回传 index, value
特别注意 index 是从 1 开始
然後下面这段 for 回圈的 code style,跟 Golang 根本一样啊
也就是 Lua function 也可以回传多个值
不知道谁学谁 XD
这个回圈只关心每次取得的档案名称,所以 index 就直接舍去了
for _, sFile in ipairs(tApis) do
-- ....
end
事实上,之前介绍的 io.lines
, string.gmatch
也都是 Lua 提供的迭代函数之一
iparis
是固定从 key index = 1 开始
然後 index = 2, index = 3 ... 循序找出 table 内的数值,遇到 nil 就停止
pairs
则没有按照顺序,但遇到 nil 不会停止,一定会把 table 内的非 nil 数值都回传
以下是测试范例
local tt =
{
[3] = "test3",
[2] = nil ,
[1] = "test1",
[5] = "test5"
}
for i, v in pairs(tt) do -- 输出 "1test1" "5test5" "3test3"
print( i .. v )
end
for i, v in ipairs(tt) do -- 输出 "1test1" 後就停止回圈,因为 tt[2] 是 nil
print( i .. v )
end
那 fs
呢 ....
这 ... 我找不到宣告 fs 的来源 QQ,只好先搁着,等待通灵的瞬间(逃~
但我想 fs 的函数应该都满直白易懂的
很容易就能猜到用途和用法
~= 在 lua 是不等於的意思
所以这一行的目的是要过滤掉隐藏档
if string.sub(sFile, 1, 1) ~= "." then
os.loadAPI()
则是在 bios.lua #521 由 CC: Tweaked 自定义的函数
虽然 Lua 也有个 os library
今天就挖矿到这里
下一回,我会来正式的研究 Lua 函数的定义
DBABootcamp 资料库管理师(Database Administrator, 简称 DBA)...
上次练习了一维阵列的阵列值位置 帮助我更了解阵列值的存放位置 那今天就要挑战更进阶的二维阵列 现在就...
前 11 天已经将常见的 concurrency patterns 介绍完毕,今天我们要介绍的不是 ...
如果有错误,欢迎留言指教~ Q_Q 上篇 Day 16 - 用 useReducer 取代 Red...
从当初进公司没有前辈的带领以及各种专案即刻救援的摧残、体验当菜鸟业师以及超新鲜面试官的经验後,现在部...