Kahibaro
Discord Login Register

2.1.5 Comments and good coding style

Why Comments Matter

When you write code in Lua for Roblox, you are also writing for your future self and for other people who might read your scripts. Comments exist to explain code in human language. Roblox Studio and the Lua interpreter ignore comments completely, so they do not affect how your game runs. Their only purpose is to help humans understand what the code is doing and why.

Good comments make scripts easier to read, easier to debug, and easier to change. Bad or missing comments can turn even simple code into something confusing. Especially as you create larger games, clear comments and consistent style become essential.

Comment Syntax in Lua

Lua supports two main types of comments: single line comments and block comments.

A single line comment starts with two hyphens, then anything after that on the same line becomes a comment. For example:

-- This is a single line comment
local speed = 16  -- Player walk speed

A block comment starts with --[[ and ends with ]]. Everything between these markers is part of the comment. This is useful for longer explanations or for temporarily disabling multiple lines of code.

--[[
This is a block comment.
You can write on multiple lines here.
Roblox will ignore all of this.
]]
local jumpPower = 50

Important rule:
Use -- for short, one line notes.
Use --[[ ... ]] for longer explanations or when you need to comment out several lines of code at once.

Writing Helpful Comments

A helpful comment answers questions that the code itself cannot easily answer. It focuses on why something is done, not just what is being done.

Consider this code without comments:

local multiplier = 1.5
local reward = baseCoins * multiplier

You can guess that a reward is being calculated, but you might not know why the multiplier is 1.5. A better version explains the intention.

-- Apply a 1.5x bonus for first time players
local multiplier = 1.5
local reward = baseCoins * multiplier

The code did not change, but the meaning became clear. If you later change the rule, you will know what to update.

Avoid comments that just repeat the code in English, such as:

-- Set speed to 16
local speed = 16

This adds no new information. Instead, explain the reason or the rule behind the number.

-- Default walk speed for all new players
local speed = 16

When to Comment and When Not To

You do not need to comment every single line. Too many comments can make code harder to read. Focus on places where someone might be confused.

Good places to add comments:

At the top of a script, to describe what the entire script is for.

Above a function, to describe what the function does and what its inputs and outputs are.

Near calculations that use special numbers or formulas that are not obvious.

Near tricky parts of the code, such as workarounds, limitations, or performance sensitive sections.

For example:

-- Handles rewards when a player finishes the obby
local function giveFinishReward(player)
    -- 100 is the base reward for completing the course
    local baseReward = 100
    -- Double the reward if the player finished under 60 seconds
    if player.leaderstats.Time.Value < 60 then
        baseReward = baseReward * 2
    end
    player.leaderstats.Coins.Value += baseReward
end

Avoid comments that will quickly become outdated, for example by copying and pasting a long description and then constantly changing the code without updating the comment. If the code and the comment disagree, the comment is worse than nothing.

Important rule:
Always keep comments accurate.
If you change how the code works, update or remove any comments that are no longer true.

Structuring Your Code Clearly

Good coding style is not only about comments. It is also about how you arrange and format your code so that it is easy to read without any extra explanation.

One part of clear structure is grouping related lines together and separating different ideas with blank lines. For example, you can group your code into sections such as configuration, references to objects, and logic.

-- Configuration
local START_HEALTH = 100
local DAMAGE_PER_HIT = 10
-- Services
local Players = game:GetService("Players")
-- Main logic
local function onPlayerAdded(player)
    player.CharacterAdded:Connect(function(character)
        local humanoid = character:WaitForChild("Humanoid")
        humanoid.Health = START_HEALTH
    end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Even before reading every detail, you can see how the script is organized. This reduces the amount of commenting you need, because the structure itself guides the reader.

Naming Variables and Functions Clearly

Names in your code act like tiny comments. Good names make your code understandable even with fewer comments. Poor names make your code confusing even with many comments.

For example, compare these two versions:

-- Hard to understand
local x = 10
local y = 1.5
local z = x * y
-- Easier to understand
local baseCoins = 10
local bonusMultiplier = 1.5
local totalReward = baseCoins * bonusMultiplier

The second version is longer to type, but you can read it almost like a sentence.

Use names that describe what a value represents, not how it is used at this exact moment. For example, playerCoins is better than c, and finishTimeSeconds is better than t.

Also try to keep a consistent naming pattern in your project. For Roblox Lua, a common style is to use lowerCamelCase for variables and functions, such as playerCoins, updateScore, and spawnCheckpoint. Constants that should not change are often written in all capital letters with underscores, like MAX_HEALTH or STARTING_COINS.

Important rule:
Prefer meaningful names over short names.
Choose names that describe what the value is, not just what you happen to do with it once.

Formatting and Indentation

Indentation is how far you push lines of code to the right. In Lua, indentation shows the structure of control blocks like if, for, and functions. Lua will run code even without indentation, but humans rely on indentation to see what belongs together.

For example, poorly formatted code like this is hard to follow:

if player then
if player.Team == "Red" then
print("On red team")
end
end

The same code with proper indentation is much clearer.

if player then
    if player.Team == "Red" then
        print("On red team")
    end
end

Use consistent spacing throughout your script. A common style is:

Use four spaces for each level of indentation.

Put spaces around operators such as =, +, -, *, /, and comparison operators like ==.

Write commas with a space after them, such as function(a, b).

For example:

local maxPlayers = 4
local bonus = score * 2
if currentPlayers < maxPlayers then
    startGame(bonus, currentPlayers)
end

The code is neat and easier to scan.

Using Comments While Debugging

Comments are also useful when you debug or test your code. Sometimes you want to temporarily disable a piece of code without deleting it. You can comment out a line or a block so that Lua ignores it while you test something else.

For a single line, place -- at the start of that line.

-- Temporarily disable extra bonus during testing
--reward = reward + 50

For several lines in a row, use a block comment.

--[[
print("Debug info:")
print("Reward:", reward)
print("Player:", player.Name)
]]

Be careful to remove or update debug comments when you finish testing. Leaving large blocks of disabled debug code can clutter your script.

Documenting Script Purpose

A good habit in Roblox development is to give each script a clear purpose and to describe that purpose at the top of the file. This is especially valuable in larger games where you might have many scripts spread across different objects.

At the top of a script you can write a short summary of what it does and how it fits into the game. For example:

--[[
Script name: ObbyCheckpointHandler
Purpose: Handles saving and loading player checkpoint positions in the obby.
This script:
1. Listens for players touching checkpoint parts.
2. Stores the last checkpoint reached.
3. Moves players back to their checkpoint on death.
]]

When you or another developer opens that script later, you will know immediately whether it is the one you need to edit.

Try to keep this top comment short but specific. You do not need to describe every detail. Focus on the main responsibilities of the script.

Style Consistency Across Your Project

Good coding style is not only about each small choice. It is also about keeping those choices consistent across the entire project. Consistent style makes it easy to move from one script to another without re-learning how things are written.

Choose patterns for your project such as:

How you name variables and functions.

How you group configuration values at the top of scripts.

How you indent and space your code.

How you write top-of-file comments for scripts and short comments inside functions.

Once you pick a style, keep using it everywhere. If you work with others, agree on a simple style upfront. Even a very basic shared style is much better than everyone writing code in completely different ways.

Consistency also helps you search for things more easily. For example, if you always call the main function to start something startGame and never begin, run, or startMatch in different places, it is easier to find that logic when you need to change it.

Important rule:
Clear, consistent style across all scripts is more important than using any particular style rule perfectly.

Comments and Style in Practice

To see how comments and style work together, consider this small example of a checkpoint script for an obby. This is not a full system, but it shows how to write clean Lua that is friendly to read.

--[[
Script name: CheckpointTouchHandler
Purpose: Records when a player touches this checkpoint part.
]]
local CHECKPOINT_NAME = "Checkpoint"
local Players = game:GetService("Players")
local checkpointPart = script.Parent
-- Returns the player that touched this checkpoint, or nil
local function getPlayerFromHit(hit)
    local character = hit.Parent
    if not character then
        return nil
    end
    local player = Players:GetPlayerFromCharacter(character)
    return player
end
local function onTouched(hit)
    local player = getPlayerFromHit(hit)
    if not player then
        return
    end
    -- Store the name of this checkpoint for the player
    player:SetAttribute(CHECKPOINT_NAME, checkpointPart.Name)
end
checkpointPart.Touched:Connect(onTouched)

The top block describes the purpose of the script. Names are descriptive. Indentation is consistent. Comments exist where the code might not be immediately obvious, such as where we explain what getPlayerFromHit returns and why we are setting an attribute.

As you build more complex games in Roblox Studio, habits like these will make your Lua scripts easier to manage, share, and extend.

Views: 22

Comments

Please login to add a comment.

Don't have an account? Register now!