Lua - Comments
Overview
Estimated time: 10–15 minutes
Comments are essential for documenting your code and making it readable for others (and yourself!). This tutorial covers single-line and multi-line comments in Lua, along with best practices for effective documentation.
Learning Objectives
- Understand the purpose and importance of comments
- Learn single-line comment syntax
- Master multi-line comment blocks
- Apply best practices for code documentation
- Use comments for debugging and code organization
Prerequisites
- Basic understanding of Lua syntax
- Ability to write and run Lua programs
Why Comments Matter
Comments serve several important purposes:
- Documentation: Explain what your code does
- Clarification: Describe complex logic or algorithms
- Maintenance: Help others (and future you) understand the code
- Debugging: Temporarily disable code during testing
- Organization: Create section headers and separators
Single-Line Comments
In Lua, single-line comments start with two dashes (--
):
-- This is a single-line comment
print("Hello, World!") -- Comment at end of line
-- Another comment explaining the next line
local x = 42
Expected Output:
Hello, World!
Comment Placement Examples
-- Program: Temperature Converter
-- Author: Your Name
-- Date: 2024
-- Get temperature in Celsius
print("Enter temperature in Celsius:")
local celsius = tonumber(io.read()) -- Convert input to number
-- Convert to Fahrenheit using formula: F = C * 9/5 + 32
local fahrenheit = celsius * 9 / 5 + 32
-- Display the result
print(celsius .. "°C = " .. fahrenheit .. "°F")
Multi-Line Comments
For longer comments, Lua uses --[[
to start and ]]
to end:
--[[
This is a multi-line comment.
It can span multiple lines.
Useful for longer explanations.
]]
print("This code will execute")
--[[
Another multi-line comment
explaining the next section
]]
local greeting = "Hello, Lua!"
print(greeting)
Expected Output:
This code will execute
Hello, Lua!
Nested Multi-Line Comments
Lua supports nested comments using different bracket levels:
--[=[
This is a level-1 multi-line comment.
--[[
This is a nested level-0 comment inside.
]]
Still part of the level-1 comment.
]=]
print("Only this line executes")
Expected Output:
Only this line executes
Commenting Best Practices
1. Header Comments
--[[
Program: Student Grade Calculator
Purpose: Calculate and display student grades with statistics
Author: Jane Smith
Date: March 2024
Version: 1.0
Dependencies:
- Lua 5.4 or higher
- No external libraries required
Usage:
lua grade_calculator.lua
]]
-- Main program starts here
local function calculate_grade(score)
-- Grade calculation logic
if score >= 90 then
return "A"
elseif score >= 80 then
return "B"
elseif score >= 70 then
return "C"
elseif score >= 60 then
return "D"
else
return "F"
end
end
2. Function Documentation
--[[
Calculate the area of a circle
@param radius: number - The radius of the circle
@return: number - The area of the circle
@example:
local area = calculate_circle_area(5)
print(area) -- Outputs approximately 78.54
]]
local function calculate_circle_area(radius)
local pi = 3.14159265359
return pi * radius * radius
end
-- Test the function
local area = calculate_circle_area(3)
print("Area of circle with radius 3:", area)
3. Section Separators
-- ============================================
-- CONFIGURATION SECTION
-- ============================================
local MAX_ATTEMPTS = 3
local DEFAULT_NAME = "Guest"
-- ============================================
-- HELPER FUNCTIONS
-- ============================================
local function validate_input(input)
return input and input ~= ""
end
-- ============================================
-- MAIN PROGRAM
-- ============================================
print("Welcome to the Lua Program!")
Comments for Debugging
Comments are useful for temporarily disabling code:
local function debug_example()
print("Starting debug example")
local x = 10
local y = 20
-- Temporarily disable this calculation
-- local result = x * y
-- print("Original result:", result)
-- Use this calculation instead for testing
local result = x + y
print("Modified result:", result)
--[[
Multi-line block comment for disabling
larger sections of code during debugging
if result > 50 then
print("Result is large")
perform_complex_operation()
end
]]
end
debug_example()
Expected Output:
Starting debug example
Modified result: 30
TODO and FIXME Comments
Use special comment markers for development notes:
-- TODO: Add input validation
-- FIXME: Handle division by zero
-- NOTE: This algorithm needs optimization
-- HACK: Temporary workaround for issue #123
local function divide(a, b)
-- FIXME: Add proper error handling for division by zero
return a / b
end
-- TODO: Implement more robust error handling
local function process_user_input(input)
-- NOTE: Currently only handles numeric input
local number = tonumber(input)
return number
end
Documentation Comments
Some developers use structured comment formats:
--[[
@module MathUtils
@description Collection of mathematical utility functions
@version 1.0
@author Your Name
]]
--[[
@function factorial
@description Calculates the factorial of a number
@param n {number} A positive integer
@return {number} The factorial of n
@throws Error if n is negative
@example
local result = factorial(5) -- returns 120
]]
local function factorial(n)
if n < 0 then
error("Factorial is not defined for negative numbers")
end
if n == 0 or n == 1 then
return 1
end
return n * factorial(n - 1)
end
-- Example usage
print("5! =", factorial(5))
Expected Output:
5! = 120
Comment Maintenance
Keep comments up-to-date with your code:
-- BAD: Outdated comment
-- Calculate sum of two numbers
local function calculate(a, b, operation) -- Now does more than sum!
if operation == "add" then
return a + b
elseif operation == "multiply" then
return a * b
end
end
-- GOOD: Updated comment
-- Perform arithmetic operation on two numbers
local function calculate(a, b, operation)
if operation == "add" then
return a + b
elseif operation == "multiply" then
return a * b
end
end
Common Pitfalls
- Over-commenting: Don't comment obvious code like
x = 5 -- Set x to 5
- Outdated comments: Update comments when you change code
- Misleading comments: Ensure comments accurately describe the code
- No comments: Complex logic should always be explained
Checks for Understanding
- How do you write a single-line comment in Lua?
- What syntax is used for multi-line comments?
- Can you nest multi-line comments in Lua?
- What are TODO comments used for?
- Why is it important to keep comments up-to-date?
Show answers
- Use
--
followed by your comment text --[[
to start and]]
to end multi-line comments- Yes, using different bracket levels like
--[=[
and]=]
- TODO comments mark areas that need future work or improvements
- Outdated comments can mislead developers and cause confusion about what the code actually does
Exercises
- Add proper comments to a previous program you wrote
- Write a function with complete documentation comments
- Practice using multi-line comments to temporarily disable code sections
Next Steps
Now that you understand how to document your code effectively, let's dive into variables and constants - the building blocks of any Lua program.