您的位置:首页 > 编程语言 > Lua

lua语言基础(4)闭包closuer

2014-05-22 17:39 351 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: