码迷,mamicode.com
首页 > 其他好文 > 详细

第五章 函数 Lua程序设计笔记

时间:2017-11-26 00:47:43      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:返回   return   div   字符串   option   fun   设计   idt   gui   

--第五章 函数
若函数只有一个参数,并且此参数时字符串或table,则圆括号可有可无

print "hello world" <--> print("hello world")
f {x = 10, y = 20} <--> f ({x = 10, y = 20})

 

--5.1多重返回值

function foo0 () end
function foo1 () return "a" end
function foo2 () return "a", "b" end


1当函数调用作为一条单独的语句时,会丢弃所有返回值。
2将函数作为表达式的一部分使用时,会保留函数的第一个返回值。
3将函数作为一系列表达式中的最后一个参数使用时,才能获得它的所有值。

x,y = foo2(), 20  -- x = "a", y = 20 不是最后一个
print(foo2())  -->a b  是最后一个
print(foo2(),1)  --> a 1  不是最后一个

 

table构造式可以接受所有的值,这是也必须是最后一个

t = {foo0()} -- t = {}
t = {foo1()} -- t = {"a"}
t = {foo2()} -- t = {"a", "b"}
t = {foo0(),foo2(),4} -- t[1] = nil, t[2] = "a", t[3] = 4   不是最后一个

 

将一个函数调用放入一对圆括号中,迫使他返回一个值:

print((foo0())) -- nil
print((foo1())) -- a
print((foo2())) -- and

 

unpack函数,接受一个数组参数,并返回其所有元素

print(unpack{10,20,30})  --> 10,20,30
a,b = unpack{10,20,30}  -- a = 10, b = 20, 30被丢弃

 

 

--5.2变长参数

function add(...)
local s = 0
for i,v in ipairs{...} do 
    s = s+v
end
return s
end

print(add(1,2,3,4,5,6))

参数列表中的三个点表示该参数可以接受不同数量的实参

 

--5.3具名实参
例如在一个GUI库中,一个用于创建新窗口的函数可能会具有很多参数,其中大部分都是可选的
使用具名实参:

w = Window{x = 0, y = 0, width = 300, height = 200, 
            title = "Lua", background = "blue",
            border = true
}

函数:(_Window才是真正调用创建窗口的函数)

function Window(options)
    if type(options.title) ~= "string" then 
        error("no title")
    elseif type(options.width) ~= "number" then
        error("no width")
    elseif type(options.height) ~= "numer" then 
        error("no height")
    end
    
    --其他参数时可选的
    _Window(options.title,
            options.x or 0,  --默认值
            options.y or 0,
            options.width, options.height,
            options.background or "white",
            options.border    --默认为false(nil)
        )
end

 

第五章 函数 Lua程序设计笔记

标签:返回   return   div   字符串   option   fun   设计   idt   gui   

原文地址:http://www.cnblogs.com/leosirius/p/7897036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!