- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- How to Call a Lua function from C?
- table.pack() function in Lua programming
- table.unpack() function in Lua programming
- math.ceil() function in Lua programming
- math.floor() function in Lua programming
- math.max() function in Lua programming
- math.modf() function in Lua programming
- select() function in Lua programming
- Sort function in Lua programming
- string.byte() function in Lua programming
- string.char() function in Lua programming
- string.format() function in Lua programming
- string.gsub() function in Lua programming
- string.lower() function in Lua programming
- string.upper() function in Lua programming

Advertisements