
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 −
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
Advertisements