Lua - Function with Named Arguments



A Lua function received parameters in positional mechanism. Whenever a function is called, its arguments are matched by their positions. First argument is for first parameter, second is for second and so on. Consider the following example−

main.lua

-- function to calculate area of a shape passed
function calculateArea(type, l, b)
   local length = l
   local breadth = b

   if type == 'Rect' then
      return length * breadth
   end
end

-- calculate area of rectangle with length as 2, width as 4
print('Area of Rectangle', calculateArea('Rect', 2, 4))

Output

When we run the above code, we will get the following output−

Area of Rectangle	8

Now if want to use named argument like following −

function calculateArea(type, length, breadth)

and call the function as −

print('Area of Rectangle', calculateArea(type='Rect', length=2, width=4))

then there is no direct support in lua to achieve it. But using table we can achieve the same. See the example below:

Using positional parameters

We can define a table which contains all the positional parameters.

arguments = { type='Rect', length=2, width=4 }

and table will be used as argument to the function.

function calculateArea(arguments)
   local length = arguments.length
   local breadth = arguments.breadth

   if arguments.type == 'Rect' then
      return length * breadth
   end
end

Complete Example of Positional Parameters

main.lua

-- function to calculate area of a shape passed
function calculateArea(arguments)
   local length = arguments.length
   local breadth = arguments.breadth

   if arguments.type == 'Rect' then
      return length * breadth
   end
end

-- calculate area of rectangle with length as 2, width as 4
print('Area of Rectangle', calculateArea({type='Rect', length=2, breadth=4}))

Output

When we run the above code, we will get the following output−

Area of Rectangle	8
Advertisements