DEV Community

Cover image for Understanding Comments in Lua
≀Paulo Portela
≀Paulo Portela

Posted on • Updated on

Understanding Comments in Lua

Introduction

The comments in Lua are useful when you need to navigate to particular parts of the code. They help move through your codes by providing some form of a foretaste. This article explores the importance of comments in Lua and provides ideas on how they can be effective in eliminating ambiguity among technical terms.

Index

  • Single Line Comments
  • Multi-Line Comments
  • Examples
  • Conclusion

Single Line Comments

Single line comments quickly explain code with just a few characters placed adjacent to each other started with two hyphens (). These give short descriptions of what is going on in the source code.

-- Let's add up some numbers
local a = 5
local b = 10
local sum = a + b  -- Storing the result in 'sum'
print("Sum:", sum) -- Showing the result
Enter fullscreen mode Exit fullscreen mode

Output:

Sum: 15
Enter fullscreen mode Exit fullscreen mode

Multi-Line Comments

For more detailed explanations, we have multiline comments. These are enclosed within --[[ and --]] symbols and provide enough room for explaining the code.

--[[
    Here's a function to figure out the area of a rectangle
    Parameters:
        width (number): The width of the rectangle
        height (number): The height of the rectangle
    Returns:
        number: The area of the rectangle
--]]
function calculateArea(width, height)
    return width * height
end
Enter fullscreen mode Exit fullscreen mode

Examples

Let's dive into a couple more examples to see how comments can make our Lua code crystal clear:

-- Example 1: Finding the square of a number
local x = 5
local square = x * x  -- Getting the square
print("Square of", x, ":", square) -- Displaying the result
Enter fullscreen mode Exit fullscreen mode

Output:

Square of 5: 25
Enter fullscreen mode Exit fullscreen mode
--[[
    Example 2: Checking if a number is even or odd
    Parameter:
        num (number): The number to check
--]]
function checkEvenOdd(num)
    if num % 2 == 0 then
        print(num, "is even")
    else
        print(num, "is odd")
    end
end

-- Let's test out some numbers
checkEvenOdd(7)
checkEvenOdd(10)
Enter fullscreen mode Exit fullscreen mode

Output:

7 is odd
10 is even
Enter fullscreen mode Exit fullscreen mode

Conclusion

Comments are like little tour guides for your Lua code. They help you and others understand what's happening and why. You can make your code more accessible and easier to maintain. So don't be shy - leave some helpful notes around your Lua scripts and watch your code clarity soar!

Top comments (0)