Lua-3---函数

来源:互联网 发布:java培训班周末靠谱吗 编辑:程序博客网 时间:2024/05/16 19:19
print("三、函数")print("1.多重返回值-----------------------")function foo2()    return 'a' , 'b'endx,y = foo2()print(x,y)-- unpack-- 接受一个数组作为参数,并从下标1开始返回数组的所有元素-- 一个函数若只有一个参数,并且此参数是一个字符串或table构造式,那么圆括号便可有可无print(unpack{10,20,30}) -- 10,20,30print(unpack({10,20,30},2)) -- 20,30-- unpack的实现--[[function unpack(t,i)    i = i or 1    if t[i] then        return t[i],unpack(t,i+1)    endend]]print("2.变长参数-----------------------")-- lua中的函数可以接受不同数量实参,例如,print时可以传入一个、两个或多个实参。function add(...)    print(...)    local s = 0    for i,v in ipairs{...} do        s = s+v    end    return sendprint(add(1,2,3,4,5))print("3.具名实参-----------------------")-- 若一个函数拥有大量的参数,而其中大部分参数可选的话,具名实参会非常有用。-- 具名实参是将所有实参组织到一个table中,并将table作为唯一的实参传给函数。function Window(options)    -- 检查必要参数    if type(options.title) ~= 'string' then        error('no title')    end    if type(options.width) ~= 'number' then        error('no width')    end    if type(options.height) ~= 'number' then        error('no height')    end    -- 其他参数可选    print(options)endWindow{x=0,y=0,width=320,height=200,title='lua',background='blue',border=true}print("4.闭合函数-----------------------")-- 若将一个函数写在另外一个函数内,那么这个位于内部的函数便可以访问外部函数中的局部变量function newCounter()    local i=0    return function()        i = i + 1        return i    endendc1 = newCounter()print(c1()) -- 1print(c1()) -- 2
0 0
原创粉丝点击