How to define and call a function in Lua Programming?


A function is a group of statements that together perform a task. You can divide up your code into separate functions.

Functions help in reducing the code redundancy and at the same time they make the code much more readable and less error prone.

In Lua, we declare functions with the help of the function keyword and then, we can invoke(call) the functions just by writing a pair of parentheses followed by the functions name.

Example

Consider the example shown below −

 Live Demo

function add(a,b) -- declaring the function
   return a + b
end
result = add(1,2) -- calling the function
print(result) -- printing the result

Output

3

Let’s consider one more example, where we will calculate the n-th Fibonacci number.

Example

Consider the example shown below −

 Live Demo

function fibonacci(n)
   if n == 0 or n == 1
      then return n
   end
   return fibonacci(n-1) + fibonacci(n-2)
end
fib = fibonacci(6)
print(fib)

Output

8

Updated on: 20-Jul-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements