Named Arguments in Lua Programming


We know that when we pass arguments to a function in any programming language, they are matched against a parameter. The first argument’s value will be stored in the first parameter, the second argument’s value will be stored in the second parameter, and so on.

Example

Consider the example shown below −

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

A("Mukul", 24, "eating")

Output

Mukul is 24 years old and likes eating

The above example works fine if we carefully pass the same argument as for the parameter it was meant for, but imagine a scenario where we mess it up.

Example

Consider the example shown below −

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

A("Mukul", "eating", 24)

Output

Mukul is eating years old and likes 24

Everything is now just chaos!

Now, what if we can name our arguments to avoid this kind of chaos. The syntax for naming our arguments is slightly different.

Example

Consider the example shown below −

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)

Output

Mukul is over 9000 years old and likes football

Updated on: 01-Dec-2021

918 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements