7.1 – Iterators and Closures
function list_iter (t)----------------------------------factory(工廠?) local i = 0 local n = table.getn(t)--------------------------回傳總元素個數 return function ()--------------------------------無名氏函式(Closure) i = i + 1 if i <= n then return t[i] end end end
t = {10, 20, 30} iter = list_iter(t) -- creates the iterator while true do local element = iter() -- calls the iterator if element == nil then break end print(element) end
1.以上會輸出10 20 30
2.LUA的陣列好像從1開始算,不像C,陣列從0開始算。
等價寫法
t = {10, 20, 30} for element in list_iter(t) do print(element) end
這裡稍微複習一下 4.3.5 – Generic for (Generic = 通用)
-- print all values of array `a'---------------------------將a陣列的值全輸出 ipairs for i,v in ipairs(a) do print(v) end
-- print all keys of table `t' for k in pairs(t) do print(k) end----------------------將a陣列的 索引 全輸出 pairs
範例:
days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
revDays = {} for i,v in ipairs(days) do revDays[v] = i end
結果會是
revDays = {["Sunday"] = 1, ["Monday"] = 2,------------索引是v,值是i。for i,v in ipairs()的寫法很容易顛倒 ["Tuesday"] = 3, ["Wednesday"] = 4, ["Thursday"] = 5, ["Friday"] = 6, ["Saturday"] = 7}
? ipairs()是回傳(值,索引) ; pairs()是回傳(索引,值)
7.2 – The Semantics of the Generic for
Semantics = 語意
for var_1, ..., var_n in explist do block end
is equivalent to the following code:
do local _f, _s, _var = explist while true do local var_1, ... , var_n = _f(_s, _var) _var = var_1 if _var == nil then break end block end end
The iterator function--------------------_f
an invariant state------------------------_s
a control variable--------------------------var_1(初始值),var_2...
if our iterator function is f, the invariant state is s,
and the initial value for the control variable is a0,
the control variable will loop over the values a1 = f(s, a0), a2= f(s, a1), and so on,
until ai is nil.
If the for has other variables, they simply get the extra values returned by each call to f
.
以下幾段是個人的感覺
那段讓人眼花撩亂的程式碼
感覺就好像是線性方程式 y=ax+b 或是f(x) = ax + b
其中ax會隨著x會變 --> a control variable
b則是 --> an invariant state
當然我的說法根源文寫的內容完全是兩碼子事。
7.3 – Stateless Iterators
a stateless iterator is an iterator that does not keep any state by itself.
Therefore, we may use the same stateless iterator in multiple loops, avoiding the cost of creating new closures
a = {"one", "two", "three"} for i, v in ipairs(a) do print(i, v) end
function ipairs (a) return iter, a, 0 end
function iter (a, i) i = i + 1 local v = a[i] if v then return i, v end end
看起來好像是因為那個In 把跟在後面的表達式 變得更複雜了
以下是簡陋筆記
for i, v in iter, a, 0 do
print(i, v) end
for i, v in iter(a, 0) do
print(i, v) end
for i, v in return 1, a[1] do
print(i, v) end
for i, v in iter, a, 1 do
print(i, v) end
for i, v in iter(a, 1) do
print(i, v) end
for i, v in return 2, a[2] do
print(i, v) end
....
pairs在LUA的原始寫法:
function pairs (t) return next, t, nil end
7.4,7.5,先留著
全站熱搜
留言列表