zoukankan      html  css  js  c++  java
  • lua学习笔记(六)

     

    (2012-04-12 23:32:35)
     
    函数
     定义
        function mytest(a,b,c) <函数体> end
        mytest = function(a,b,c) <函数体> end
        local function mytest(a,b,c) <函数体> end
        local mytest = function(a,b,c) <函数体> end
        t = {} t.mytest = function(a,b,c) <函数体> end
        t = { mytest = function(a,b,c) <函数体> end}
        t = {} function t.mytest(a,c,b) <函数体> end
     
      调用
        基本调用 
            a,b,c = mytest(1,2,3)
        冒号语法糖调用
            o.foo(o,x) = o:foo(x) 
            使用冒号调用时会把冒号前的内容当作函数的第一个参数传入
        多重返回值
            function mytest()
                    return 1,2,3
            end
            a,b = mytest()
            assert(a==1 and b==2)
            a,b,c,d = mytest()
            assert(c==3 and d==nil)
            assert(select("#",mytest()==3))
        变长参数
            function mytest(...)
                    a,b=...
                    return a,b
            end
            a,b = mytest(1,2)
            assert(a==1 and b==2)
             "..."是表达式,代表变长参数如:return ...就是返回所有传入的参数
            {...}代表所有变长参数的集合,可以象使用table的一样访问也可以用ipairs{...}遍历
            select函数操作访问变长参数的能力
            select(n, ...)访问第n个参数
            select("#", ...)获得参数个数
        特殊调用
            当函数仅有一个参数并且是字符串时可以使用 mytest "wangning"方式,不用写()
            当函数仅有一个参数并且是table时可以使用 mytest {a=1, b=2, c=3}的方式,不用写()
        具名实参
            function showwindow(opt)
                    print(opt.x)
                    print(opt.y)
                     print(opt.title)
                    print(opt.text)
            end
            showwindow {x=0, y-0, title="hi!", text="helloworld"}
     
      闭包(词法域)
        在函数内定义函数,内部函数可以访问外部函数的变量
            function mytest()
                    local i = 0
                    return function()
                    i = i + 1
                    return i
                    end
            end
            my = mytest()
            print(my()) --> 1
            print(my()) --> 2
            my1 = mytest()
            print(my1()) -->1
            print(my1()) -->2
            print(my()) --> 3
        函数式编程的基础
        可以实现如迭代器之类的功能,实用性很高
        这种形式就是实现了单一功能的类的对象
     
      尾调用消除 tail-call elimination
        最后一句如果是一个函数调用就是尾调用
        相当于goto,也可用于状态机
        当前函数真正结束,不会在栈中了
        return <func>(<args>)才是真正的尾调用
        function f(x) g(x) end不是尾调用,它还会回来
     
  • 相关阅读:
    Laravel 出现 No application encryption key has been specified.
    windows下用composer局部安装laravel
    vue组件--通讯录
    vue组件--TagsInput
    axios封装(二)队列管理
    axios封装(一)基础配置
    [git hooks] pre-commit 配置
    qs.js
    flexbox的应用
    盒子模型详解
  • 原文地址:https://www.cnblogs.com/lifesteven/p/4169372.html
Copyright © 2011-2022 走看看