第一版是为 Lua 5.0 编写的。虽然在很大程度上仍然适用于更高版本,但还是有一些不同之处。
第四版针对 Lua 5.3,可在 Amazon 和其他书店购买。
购买本书,您还可以帮助支持 Lua 项目。
![]() |
用 Lua 编程 | ![]() |
| 第一部分。语言 第 5 章。函数 |
Lua 中的参数传递机制是按位置的:当我们调用函数时,参数按其位置与参数匹配。第一个参数将值赋给第一个参数,依此类推。但是,有时按名称指定参数会很有用。为了说明这一点,让我们考虑函数 rename(来自 os 库),它重命名一个文件。我们经常忘记哪个名称在前,新名称还是旧名称;因此,我们可能希望重新定义此函数以按名称接收其两个参数
-- invalid code
rename(old="temp.lua", new="temp1.lua")
Lua 不直接支持该语法,但我们可以通过一个小小的语法更改获得相同的效果。此处的想法是将所有参数打包到一个表中,并使用该表作为函数的唯一参数。Lua 为函数调用提供的特殊语法,仅将一个表构造函数作为参数,有助于实现此技巧
rename{old="temp.lua", new="temp1.lua"}
因此,我们仅使用一个参数定义 rename,并从此参数获取实际参数
function rename (arg)
return os.rename(arg.old, arg.new)
end
当函数有许多参数且大多数参数都是可选时,这种参数传递方式特别有用。例如,GUI 库中创建新窗口的函数可能有多个参数,其中大多数是可选的,最好按名称指定这些参数
w = Window{ x=0, y=0, width=300, height=200,
title = "Lua", background="blue",
border = true
}
然后,Window 函数可以自由检查必需的参数、添加默认值等。假设一个原始的 _Window 函数实际上创建了新窗口(并且需要所有参数),我们可以如下定义 Window
function Window (options)
-- check mandatory options
if type(options.title) ~= "string" then
error("no title")
elseif type(options.width) ~= "number" then
error("no width")
elseif type(options.height) ~= "number" then
error("no height")
end
-- everything else is optional
_Window(options.title,
options.x or 0, -- default value
options.y or 0, -- default value
options.width, options.height,
options.background or "white", -- default
options.border -- default is false (nil)
)
end
| 版权所有 © 2003–2004 Roberto Ierusalimschy。保留所有权利。 | ![]() |