• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
梦想照进灵魂
博客园    首页    新随笔    联系   管理    订阅  订阅
LUA 拾遗(函数)

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

(传参)

function Window (options)
    -- check mandatory options
    if type(options.title) ~= "string" then
    error("no title" )
    elseif type(options.width) ~= "number" then
    error("no width" )
    elseif type(options.height) ~= "number" then
    error("no height")
    end
    print(options.title)
end

w = Window {
    x=0, y=0, width=300, height=200,
    title = "-- > mark" , background= "blue",
    border = true
}

 

(闭包)

function newCounter() 
  local i = 0 
  return function () -- anonymous function 
    i = i + 1 
   return i 
  end 
end 
 
c1 = newCounter() 
print(c1()) --> 1 
print(c1()) --> 2

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

 

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

function allwords()
    local file = io.open("test.lua", "r")
    local line = file:read() -- current line
    local pos = 1 -- current position in the line
    return function () -- iterator function
        while line do -- repeat while there are lines
            local s, e = string.find(line, "%w+" , pos)
            if s then -- found a word?
                pos = e + 1 -- next position is after this word
                return string.sub(line, s, e) -- return the word
            else
                line = file:read() -- word not found; try next line
                pos = 1 -- restart from first position
            end
        end
        file:close()
        return nil -- no more lines: end of traversal
    end
end

for word in allwords() do
    print(word)
end

 

posted on 2013-05-02 22:13  梦想照进灵魂  阅读(196)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3