Lua学习笔记(四)

来源:互联网 发布:华为数据库一体机 编辑:程序博客网 时间:2024/06/01 10:09

5、函数
语法:
function func_name (arguments-list)
statements-list;
end;
Lua 也提供了面向对象方式调用函数的语法,比如 o:foo(x)与 o.foo(o, x)是等价的
Lua 函数实参和形参的匹配与赋值语句类似,多余部分被忽略,缺少部分用 nil 补足
5.1 多返回值
Lua 函数可以返回多个结果值,比如 string.find,其返回匹配串“开始和结束的下标”
(如果不存在匹配串返回 nil)。
这里写图片描述
Lua 函数中,在 return 后列出要返回的值得列表即可返回多值,如
这里写图片描述
返回最大值以及最大值的位置
这里写图片描述
一个 return 语句如果使用圆括号将返回值括起来也将导致返回一个值
类似Java的public void test(String ..args)
Lua 函数可以接受可变数目的参数,和 C 语言类似在函数参数列表中使用三点(…)
表示函数有可变的参数。Lua 将函数的参数放在一个叫 arg 的表中,除了参数以外,arg
表中还有一个域 n 表示参数的个数。
重写print

function print(...)for i,v in ipairs(arg) doprintResult = printResult .. tostring(v) .. "\t"endprintResult = printResult .. "\n"end

有时候我们可能需要几个固定参数加上可变参数
function g (a, b, …) end
如果我们只想要 string.find 返回的第二个值。一个典型的方法是
使用哑元(dummy variable,下划线):
还可以利用可变参数声明一个 select 函数:
function select (n, …)
return arg[n]
end
这里写图片描述
有时候需要将函数的可变参数传递给另外的函数调用,可以使用前面我们说过的
unpack(arg)返回 arg 表所有的可变参数,Lua 提供了一个文本格式化的函数 string.format
(类似 C 语言的 sprintf 函数):
function fwrite(fmt, …)
return io.write(string.format(fmt, unpack(arg)))
end
5.3 命名参数
Lua 的函数参数是和位置相关的,调用时实参会按顺序依次传给形参
– invalid code
rename(old=”temp.lua”, new=”temp1.lua”)
当函数的参数很多的时候,这种函数参数的传递方式很方便的。例如 GUI 库中创建
窗体的函数有很多参数并且大部分参数是可选的,可以用下面这种方式:

w = Window {x=0, y=0, width=300, height=200,title = "Lua", background="blue",border = true}function Window (options)-- check mandatory optionsif type(options.title) ~= "string" thenerror("no title")elseif type(options.width) ~= "number" thenerror("no width")elseif type(options.height) ~= "number" thenerror("no height")end-- everything else is optional_Window(options.title,options.x or 0,  -- default valueoptions.y or 0,  -- default valueoptions.width, options.height,options.background or "white", -- defaultoptions.border  -- default is false (nil))end

未完待续…

0 0
原创粉丝点击