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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP