Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15325
  • 博文数量: 3
  • 博客积分: 70
  • 博客等级: 民兵
  • 技术积分: 40
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-05 22:08
文章分类

全部博文(3)

文章存档

2013年(3)

最近访客

分类: PERL

2013-05-01 02:03:55

(返回值)
        return arg[n]     -- 返回第n个返回值,index从1开始

(传参)

点击(此处)折叠或打开

  1. function Window (options)
  2.     -- check mandatory options
  3.     if type(options.title) ~= "string" then
  4.     error("no title" )
  5.     elseif type(options.width) ~= "number" then
  6.     error("no width" )
  7.     elseif type(options.height) ~= "number" then
  8.     error("no height")
  9.     end
  10.     print(options.title)
  11. end

  12. w = Window {
  13.     x=0, y=0, width=300, height=200,
  14.     title = "-- > mark" , background= "blue",
  15.     border = true
  16. }
(闭包

点击(此处)折叠或打开

  1. function newCounter()
  2.   local i = 0
  3.   return function () -- anonymous function
  4.     i = i + 1
  5.    return i
  6.   end
  7. end
  8.  
  9. c1 = newCounter()
  10. print(c1()) --> 1
  11. print(c1()) --> 2

关键在于理解upvalue(external local variable ), 这个变量是每个闭包独有的且是静态的

(强大的迭代器) -- 一般难写易用

点击(此处)折叠或打开

  1. function allwords()
  2.     local file = io.open("test.lua", "r")
  3.     local line = file:read() -- current line
  4.     local pos = 1 -- current position in the line
  5.     return function () -- iterator function
  6.         while line do -- repeat while there are lines
  7.             local s, e = string.find(line, "%w+" , pos)
  8.             if s then -- found a word?
  9.                 pos = e + 1 -- next position is after this word
  10.                 return string.sub(line, s, e) -- return the word
  11.             else
  12.                 line = file:read() -- word not found; try next line
  13.                 pos = 1 -- restart from first position
  14.             end
  15.         end
  16.         file:close()
  17.         return nil -- no more lines: end of traversal
  18.     end
  19. end

  20. for word in allwords() do
  21.     print(word)
  22. end


阅读(1314) | 评论(0) | 转发(0) |
0

上一篇:LUA 拾遗(表的构造、流程控制)

下一篇:没有了

给主人留下些什么吧!~~