How to use the require function in Lua programming?


Lua offers a high-level function which we can use when we want to load and run libraries. This high-level function is named require function.

The require function mainly targets the high level functions and keywords.

The require function is a bit similar to the dofile function, but it has two key differences, the first one being that it searches for the file in a specified path and the second one is that it mainly focuses on to control whether the file is already running on the script or not.

Syntax

require “module-name”
// some code

How Does the require Function Work in Lua?

  • It is mainly used to import other modules like file, image, etc. It requires and includes some packages that accept some global variables and functions.
  • It includes other libraries using find keywords with which we can find the files and data.
  • It also accepts the customized methods and scripts which have been created by the end user.

Example

Let’s consider an example where we will make Lua files, namely First.lua and Second.lua and then see how we can import the function that was written in the First.lua file and then invoke the code from the Second.lua file.

Consider the example shown below −

First.lua file −

 Live Demo

function Min(n1, n2)
if (n1 < n2) then
result = n1;
else
result = n2;
end
return result;
end
print("The Minimum of the two numbers is ",Min(112,421))
print("The Minimum of the two numbers is ",Min(13,8))
print("The Minimum of the two numbers is ",Min(11,3))
print("The Minimum of the two numbers is ",Min(12,8))

The above function is used to find the minimum number of the two numbers that we pass as an argument to the Min function.

Second.lua file −

require ("First")

In the above file, we are telling the Lua compiler that we require the module named “First”

Now if we run the following command to the terminal, we will see that the code inside the First.lua will be executed.

lua Second.lua

Output

The Minimum of the two numbers is 112
The Minimum of the two numbers is 8
The Minimum of the two numbers is 3
The Minimum of the two numbers is 8

Updated on: 20-Jul-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements