Lua Modules Tutorial – Complete Guide

Welcome to this engaging tutorial on ‘Lua modules.’ In this journey, we will delve into what Lua Modules are, why you should be learning them, and how they can be implemented practically.

What is Lua?

Lua is a powerful, efficient, and lightweight programming language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description. Lua combines straightforward procedural syntax with powerful data description constructs based on associations and extensibility.

What are Lua Modules?

In Lua, modules are like mini-libraries. They are a way to organise and package related functions so that they can be used repeatedly. Lua modules aid the organization and reusability of code, ultimately simplifying development and debugging.

Why Should I Learn Lua and its Modules?

With the emergence of platforms like Roblox, Lua has garnered a sense of popularity amongst game developers. Learning about Lua and how its modules work is instrumental in expanding your coding skills and understanding of game logic. Its straightforward syntax and modular system make Lua a great starting point for beginners interested in game development, and a powerful tool in the arsenal of experienced developers.

CTA Small Image

FREE COURSES AT ZENVA

LEARN GAME DEVELOPMENT, PYTHON AND MORE

AVAILABLE FOR A LIMITED TIME ONLY

Creating a Simple Lua Module

To start with, let’s create a simple Lua module. We’ll create a module that performs basic mathematical operations such as addition, subtraction, multiplication, and division.

-- File saved as calc.lua
local calc = {}
 
function calc.add(a, b)
   return a + b
end

function calc.sub(a, b)
   return a - b
end

function calc.mul(a, b)
   return a * b
end

function calc.div(a, b)
   return a / b
end
 
return calc

In the above code, we start by creating a new table ‘calc.’ Then, we add four functions to perform basic mathematical operations, taking two arguments each. Finally, we return calc to make these functions accessible from outside the module.

Using Lua Modules

Once a module is created, it can be easily used in Lua using the ‘require’ statement. Let’s use our ‘calc’ module to calculate some values.

-- Requiring our calc module
local calc = require("calc")

print(calc.add(10, 20))  -- This will print 30
print(calc.sub(40, 15))  -- This will print 25
print(calc.mul(2, 4))    -- This will print 8
print(calc.div(100, 25)) -- This will print 4

In this code, we use the ‘require’ keyword to include the previously created ‘calc’ module. After importing the function from the module, we apply our math operations and print the results.

Another Module Example

Let’s create one more module named ‘simpleMath’ to understand Lua modules better.

This module will consist of two functions: one to calculate the square of a number, and one to calculate the square root.

-- File saved as simpleMath.lua
local simpleMath = {}

function simpleMath.square(a)
   return a * a
end

function simpleMath.sqrt(a)
   return math.sqrt(a)
end

return simpleMath

The module simpleMath allows us to calculate the square and square root of a number. The code calls built-in Lua functionality to perform the square root calculation.

Now let’s use our ‘simpleMath’ module.

-- Requiring our simpleMath module
local simpleMath = require("simpleMath")

print(simpleMath.square(10))  -- This will print 100
print(simpleMath.sqrt(25))   -- This will print 5

After requiring the ‘simpleMath’ module, we’re able to call the ‘square’ and ‘sqrt’ methods as we did earlier with the ‘calc’ module.

Advanced Module Creation

In Lua, module functions do not always need to be associated with a table. Lua functions are first-class entities, meaning they can be stored in variables and passed as parameters.

This flexibility allows us to create our functions directly in the globalnamespace, making them directly accessible.

Let’s use this methodology to create an ‘advancedMath’ module.

-- File saved as advancedMath.lua
function power(base, exponent)
    return math.pow(base, exponent)
end

function factorial(n)
    return math.factorial(n)
end

In the code above, we have defined two advanced math operations in the global namespace – computing the power of a number and calculating the factorial. Note that these functions will be visible only to this file.

Accessing Global Functions from Modules

To access the global functions inside ‘advancedMath’ from another script, we ‘require’ the module as usual.

-- Requiring our advancedMath module
require("advancedMath")

-- Use the global functions
print(power(2,3))  -- This will print 8
print(factorial(5)) -- This will print 120

In the code above, we ‘required’ the ‘advancedMath’ module and used the global functions ‘power’ and ‘factorial’ directly without any module reference.

Inheritance among Modules

Lua also supports inheritance between modules, which is crucial when organising large codebases.

Let’s create a ‘shapes’ module that contains general methods applicable to all shapes. Then, we’ll create a ‘rectangle’ module that inherits from ‘shapes.’

-- File saved as shapes.lua
local shapes = {}

function shapes.getArea(length, breadth)
    return length * breadth
end

function shapes.getPerimeter(length, breadth)
    return 2 * (length + breadth)
end

return shapes

Now, let’s create the ‘rectangle’ module.

-- File saved as rectangle.lua
local shapes = require("shapes")
local rectangle = shapes

return rectangle

In this example, the ‘rectangle’ module inherits all the methods from the ‘shapes’ module, allowing us to calculate the area and perimeter of a rectangle.

-- Requiring our rectangle module
local rectangle = require("rectangle")

print(rectangle.getArea(5, 10))             -- This will print 50
print(rectangle.getPerimeter(5, 10))        -- This will print 30

In this last snippet, we require the ‘rectangle’ module and utilize its inherited methods to calculate the area and perimeter of a rectangle. This inherits all methods from the ‘shapes’ module.

By using Lua modules and their inheritance capabilities, we can keep our code organised, clean, and reusable, making our programming experience more efficient and enjoyable. Moreover, it would allow us to create complex applications with thousands of lines of codes in a more manageable way.

Multiple Inheritance Among Modules

Not only can a Lua module inherit from a single module, but it can also inherit from multiple modules. This is termed as ‘multiple inheritance.’ Let’s understand this concept with a practical example.

We will use our existing ‘shapes’ module and create a new module ‘circle’, defining functions to calculate the area and circumference of a circle.

-- File saved as circle.lua
local circle = {}

function circle.getArea(radius)
    return math.pi * radius * radius
end

function circle.getCircumference(radius)
    return 2 * math.pi * radius
end

return circle

Now, let’s create a new module ‘shapesUtils’ that will inherit both ‘shapes’ and ‘circle’ modules.

-- File saved as shapesUtils.lua
local shapes = require("shapes")
local circle = require("circle")
local shapesUtils = {}

shapesUtils = setmetatable(shapesUtils, {
    __index = function(t, k)
        return shapes[k] or circle[k]
    end
})

return shapesUtils

In the `shapesUtils` module, we use the `setmetatable` function. This function sets a metatable for the target. A metatable is an invisible table that can perform a set of functions whenever the table is accessed. Here we have overridden the `__index` function so that it can handle undefined fields.

With the new `shapesUtils` module, we can now perform functions like ‘getArea’ and ‘getPerimeter’ of a rectangle and also the ‘getArea’ and ‘getCircumference’ of a circle from one module.

-- Requiring our shapesUtils module
local shapesUtils = require("shapesUtils")

print(shapesUtils.getArea(5, 10))             -- This will print 50
print(shapesUtils.getPerimeter(5, 10))        -- This will print 30
print(shapesUtils.getArea(7))                 -- This will print 153.938
print(shapesUtils.getCircumference(7))        -- This will print 43.96

At this point, we have reduced our code’s redundancy and increased its efficiency and readability by using Lua modules and multiple inheritance.

Conclusion

Lua modules are a staple of efficient, reusable, and scalable code. They allow us to group related functions in an organized manner, drastically reducing redundancy and promoting code reusability. Modules simplify code debugging, refactorizations, and improvements, making your coding journey more efficient and enjoyable.

By implementing the concepts of inheritance and multiple inheritance, we can write elegant and powerful code that represents real-world objects and their relationships. With this tutorial, you are now able to implement Lua modules and can explore more of Lua’s powerful features. Happy Coding!

Where to Go Next?

We’ve already made a significant stride in understanding Lua and its modules, but learning should always be a continuous journey. One of the best ways to keep advancing your Lua programming skills is through our Roblox Game Development Mini-Degree. This comprehensive collection of courses covers various genres of game creation, including obstacle courses, melee combat, and FPS games, with the functionality of Roblox Studio and Lua.

Broadening Your Skills

Zenva offers a wide range of over 250 supported courses, capable of taking you from a beginner to a professional. Our courses are tailored to help you learn vital coding skills, create engaging games, and earn valuable certificates in the process. For a broader look into Lua and Roblox, don’t hesitate to check our extensive collection of Roblox courses.

By aligning yourself with Zenva’s high-quality and flexible curriculum, you give yourself a stand-out advantage in the game development industry, opening a world of exciting opportunities. So, let’s keep that momentum going and continue exploring the incredible world of coding and game development with Zenva!

Conclusion

Learning Lua modules is a vital step in mastering Lua, especially in Roblox game development. It brings you closer to creating dynamic, engaging, and highly efficient games, capable of bringing your imaginations to life. The application of Lua modules and inheritance extends beyond just creating games and finds its use in several coding endeavours.

Keeping this momentum, continue exploring and enhancing your repertoire of game development skills with Zenva’s in-depth, project-based tutorials. For those who are ready to take their Lua and Roblox expertise to the next level, we highly recommend our Roblox Game Development Mini-Degree. Get started today and code your way to creating amazing games and, ultimately, an exciting career in game development!

FREE COURSES

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.