lua advanced function

来源:互联网 发布:广告软件 编辑:程序博客网 时间:2024/05/17 00:14
接受函数作为参数的函数成为”高阶函数“

network = {
     {name= "gramma", IP = "210.26.30.34"},
     {name= "arrial", IP = "210.26.30.35"},
     {name= "lua", IP = "210.26.30.36"},
     {name= "cplus", IP = "210.26.30.37"},
     {name= "dephi", IP = "210.26.30.38"},
}

以name字段来对table排序
     table.sort(network, function (a,b) (a.name > b.name) end)


function derivative (f, delta)
     delta = delta or 1e-4
     return function (x)
          return (f(x + delta) - f(x))/delta
      end
end

闭合函数Closure

     function newCounter()
         local i = 0
               return function ()
                    i = i + 1
                    return i
                end
       end

c1 = newCounter()

print(c1())                          -->1
print(c1())                          -->2

非全局函数
     函数不仅可以存储在全局的变量中,还可以存储在table的字段和局部变量中

---[[
lib = {}
lib.foo = function (x, y) return x + y end
lib.goo = function (x, y) return x - y end

lib = {
     foo = function (x, y) return x + y  end
     goo = function (x, y) return x - y end
}

lib = {}
function lib.foo (x, y) return x + y end
function lib.goo (x, y) return x - y end
--]]


--[[
function values (t)
     local i = 0
     return function () i = i + 1;
                    return t[i]
     end
end

t= {10, 20, 30}
iter = values(t)
while true do
     local element = iter()
     if element == nil then break end
          print(element)
end

--]]


--[[
function allwords ()
     local line = io.read()
     local pos = 1
     return function ()
          while line do
               local s, e = string.find(line, "%w+", pos)
               if s then
                    pos = e + 1
                    return sting.sub(line,s,e)
               else
                    line = io.read()
                    pos = 1
              end
        end
        return nil
     end
end

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

--]]


0 0