lua语言基础(4)闭包closuer

来源:互联网 发布:网易我的世界 linux 编辑:程序博客网 时间:2024/06/08 18:51


1. 回调一般发生在digitbutton函数执行完之后,那个时候局部变量digit已经超出了作用范围,但closuer仍可以访问。

function digitButton (digit)
      return Button{ label = digit,
                     action = function ()
                                add_to_display(digit)
                              end
                   }
    end

 

2. Hook原来的函数

do

     local oldSin = math.sin

     local k = math.pi/180

     math.sin = function (x)

       return oldSin(x*k)

     end

    end

 

do
      local oldOpen = io.open
      io.open = function (filename, mode)
        if access_OK(filename, mode) then
          return oldOpen(filename, mode)
        else
          return nil, "access denied"
        end
      end
    end

 

3. lua的尾调用可以防止堆栈溢出

 

function foo (n)
      if n > 0 then return foo(n - 1) end
    end

 

不是:

function f (x)
      g(x)
      return
    end

 

return g(x) + 1     -- must do the addition
    return x or g(x)    -- must adjust to 1 result
    return (g(x))       -- must adjust to 1 result

 

4 . 一个例子:实现状态机

function room1 ()
      local move = io.read()
      if move == "south" then return room3()
      elseif move == "east" then return room2()
      else print("invalid move")
           return room1()   -- stay in the same room
      end
    end
    
    function room2 ()
      local move = io.read()
      if move == "south" then return room4()
      elseif move == "west" then return room1()
      else print("invalid move")
           return room2()
      end
    end
    
    function room3 ()
      local move = io.read()
      if move == "north" then return room1()
      elseif move == "east" then return room4()
      else print("invalid move")
           return room3()
      end
    end
    
    function room4 ()
      print("congratulations!")
    end
0 0
原创粉丝点击