LUA 拾遗(函数)

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

 

转载于:https://www.cnblogs.com/mark-huang/archive/2013/05/02/3055527.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值