Lua 编程中的命名参数

我们知道,当我们将参数传递给任何编程语言的函数时,它们都会与参数匹配。第一个参数的值将存储在第一个参数中,第二个参数的值将存储在第二个参数中,依此类推。

示例

考虑下面显示的例子 -

local function A(name, age, hobby)
   print(name .. " is " .. age .. " years old and likes " .. hobby)
end

A("Mukul", 24, "eating")
输出结果
Mukul is 24 years old and likes eating

如果我们小心地传递与它要传递的参数相同的参数,上面的例子就可以正常工作,但是想象一下我们把它搞砸的场景。

示例

考虑下面显示的例子 -

local function A(name, age, hobby)
   print(name .. " is " .. age .. " years old and likes " .. hobby)
end

A("Mukul", "eating", 24)
输出结果
Mukul is eating years old and likes 24

现在一切都只是混乱!

现在,如果我们可以命名我们的论点以避免这种混乱怎么办?命名参数的语法略有不同。

示例

考虑下面显示的例子 -

local function B(tab)
   print(tab.name .. " is " ..tab.age.. " years old and likes " .. tab.hobby)
end

local mukul = {name="Mukul", hobby="football", age="over 9000", comment="plays too much football"}

B(mukul)
输出结果
Mukul is over 9000 years old and likes football