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
- lua语言基础(4)闭包closuer
- [Lua]Lua语言基础汇总(4) -- 函数
- 用lua写一个闭包的例子(lua语言)
- 0基础lua学习(十二)Lua 模块与包
- lua进阶4--lua闭包
- [Lua]lua闭包
- [Lua]Lua语言基础汇总(1) -- 类型与值
- [Lua]Lua语言基础汇总(2) -- 表达式
- [Lua]Lua语言基础汇总(3) -- 语句
- lua语言基础(2)函数
- lua语言基础(3)变长参数
- LUA语言基础
- Lua语言基础
- Lua语言基础入门
- lua语言基础
- LUA语言基础
- Lua语言基础
- LUA语言基础
- 自动引用计数(ARC)必须遵守一些规则
- Android 浮动搜索框 searchable 使用指南
- 常用的正则校验类
- 同问。kindeditor在母版页里不显示解决办法
- flex 强制转换类型失败无法将object转换为XXX
- lua语言基础(4)闭包closuer
- C/C++ 指针部分总结1
- Uploadify在IE、火狐上上传时报406这个HTTP异常解决方案
- PAT1009. 说反话
- 启动Tomcat6.x时manager does not exist or is not a readable directory
- 大数据究竟是什么?一篇文章让你认识并读懂大数据
- Java中异常详解
- jQuery验证控件jquery.validate.js使用说明+中文API
- JSON.stringify 语法讲解