(返回值)
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)endw = 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 endendfor word in allwords() do print(word)end