close

筆記模式

================================================

lexical scoping(查翻譯是:詞法作用域)

When a function is written enclosed in another function, it has full access to local variables from the enclosing function.

簡單說就是函數中還有函數。

例如

function a()

   ....

  function ()-------------------一定不能有任何名稱,叫做無名式函式

   ....

   return XXX

  end

end

 

無名式函式已經被a()包進去了。

此時的無名式函式,可以存取a()裡的變數,

另外注意無名式函式一定要return,因為它有一個驚人的作用,

例如以下函式(借來的)

function newCounter ()
      local i = 0
      return function ()   -- 無名式函式
               i = i + 1
               return i
             end
    end
    
    c1 = newCounter()
    print(c1())  --> 1
    print(c1())  --> 2
 
 
咦?i不是區域變數嗎?
怎麼print第二次的輸出值就累加了?
再往下看例子
c2 = newCounter()
    print(c2())  --> 1
    print(c1())  --> 3
    print(c2())  --> 2
So, c1 and c2 are different closures over the same function and each acts upon an independent instantiation of the local variable i.
using the concept of closure

=================================================
 
function f (x)
      return g(x)
end
g(x) 是 Proper Tail Calls
因為回傳g()後f()就沒事做了
 
由於此特性
下面函式的n值無論再大都不會溢出
function foo (n)
      if n > 0 then return foo(n - 1) end
end
==================================================
arrow
arrow
    全站熱搜

    abcdefg 發表在 痞客邦 留言(0) 人氣()