lua语言基础(4)闭包closuer
2014-05-22 17:39
351 查看
1. 回调一般发生在digitbutton函数执行完之后,那个时候局部变量digit已经超出了作用范围,但closuer仍可以访问。
2. Hook原来的函数
do
local oldSin = math.sin
local k = math.pi/180
math.sin = function (x)
return oldSin(x*k)
end
end
3. lua的尾调用可以防止堆栈溢出
不是:
4 . 一个例子:实现状态机
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
相关文章推荐
- [转]Lua语言基础汇总(5) -- 闭包
- Lua语言基础汇总(5) -- 闭包
- eLua学习第三课:Lua脚本语言的基础入门教程
- 【COCOS2DX-LUA 脚本开发之二】LUA语言基础
- lua语言基础(3)变长参数
- [转]Lua语言基础汇总(3) -- 语句
- [Lua]Lua语言基础汇总(4) -- 函数
- [Lua]Lua语言基础汇总(2) -- 表达式
- lua语言中闭包的学习心得
- lua语言基础(1)一些零散的语法
- Lua语言基础
- [Lua]Lua语言基础汇总(3) -- 语句
- 【COCOS2DX-LUA 脚本开发之二】LUA语言基础
- lua语言的闭包问题 求解
- lua 语言基础
- lua语言基础(2)函数
- [ IOS-Cocos2d-x 游戏开发] - Lua 开发之一(Lua-基础语言学习)
- 【COCOS2DX-LUA 脚本开发之一】LUA语言基础在Cocos2dX游戏中使用Lua脚本进行游戏开发(基础篇)并介绍脚本在游戏中详细用途
- 【COCOS2DX-LUA 脚本开发之二】LUA语言基础
- Cocos2d-x-Lua (2.x)脚本开发之 Lua语言基础