Code Formatting Etiquette

Hi! As of late, the Developer Forum has rapidly been growing in size and there are more and more topics being created in #development-support:scripting-support. Although most code pieces posted here are fine, there are some pieces of code that aren’t formatted well enough to be read easily. There’s a downside to having these kinds of code: it makes it harder for others to help you.

Why?

Some people think it’s fine simply because you’re the only one scripting and sure it’s fine if you like it that way but it’s not okay when giving your code to someone else for review or as a “good”. Indenting your code makes it easier for other people to help you and other people to better understand your code. Take a look at the following code:

Poorly formatted code
function mystery.OnServerInvoke(Player, lot)
local playerData = PermissionsHandler.GetPlayer(Player);
if not playerData.hasLot and not playerData.inTeam then
PermissionsHandler.ClaimLot(lot, Player)
return true
else
local Snackbar = PseudoInstance.new("Snackbar")
Snackbar.Text = 'You are already associated with ' .. playerData.lot .. '!'
Snackbar.Parent = Player
return false
end
end

How long does it take for you figure out what the code below is supposed to do as opposed to the same code segment with indentation and line breaks?

Better formatted code
function ClaimLot.OnServerInvoke(Player, lot)
	local playerData = PermissionsHandler.GetPlayer(Player);

	if not playerData.hasLot and not playerData.inTeam then
		PermissionsHandler.ClaimLot(lot, Player)
		return true
	else
		local Snackbar = PseudoInstance.new("Snackbar")
		Snackbar.Text = 'You are already associated with ' .. playerData.lot .. '!'
		Snackbar.Parent = Player
		return false
	end

end

If I needed help with the code above and why there was always a Snackbar being sent out, you could probably tell me why a lot quicker.

General Formatting Tips

Indentations

First off, indentations, they’re incredibly useful as you saw in the code blocks above. Indentations help programmers that are more experienced and/or less familiar with your work figure out what your code is supposed to do. When indenting, it’s a good rule of thumb to indent one level inwards as you go deeper within your function (another function, loops, if statements, and statements). You can see how this works here:

function getFullLengthOfArray(array)
    -- we're one level into this function and all of the code below
    -- is one also indented at least one level inwards to show that it's
    -- contained within getFullLengthOfArray
    local count = 0
    for _, object in pairs (array) do
         -- when going inside a loop, indent the "action" code inside the loop 
         -- one level inwards
         if typeof(object) == "table" then
             -- when going inside a conditional statement, indent the consequential
             -- (and alternative code, if applicable) one level inwards
             count = count + getFullLengthOfArray(object)
         else
             count = count + 1
         end
    end
    -- be sure to unindent when you've left that scope
    return count
end

When indenting properly, you should not expect to see code that’s uneven with each other in terms of their indentation levels.

Vertical Whitespace

Vertical whitespace is also important as well. The code block above purposely has no vertical whitespace and you see how heavy it looks on the eyes without it. Vertical whitespace helps break code up into different parts which allows people to figure out which each code segment is supposed to do. For example, you would break a function that resets the game after a round into different parts where each has it’s own “role”. One part would be cleaning the game field and another part would be respawning the players. You should generally include vertical whitespace between different functions, for loops, and if statements. You can cluster a group of statements together when they’re related to one another like so:

function PartsCreator()

    local partA = Instance.new("Part")
    partA.Name = "PartA"
    partA.Position = Vector3.new(0, 0, 0)
    partA.BrickColor = BrickColor.new("Really red")
    partA.Parent = workspace;

    local partB = Instance.new("Part")
    partB.Name = "PartA"
    partB.Position = Vector3.new(0, 5, 0)
    partB.BrickColor = BrickColor.new("Really blue")
    partB.Parent = workspace;

    for _, object in pairs (workspace:GetChildren()) do
         if object:IsA("BasePart") then

             if object.BrickColor == "Really red" then
                  -- do something
             end

             if object.Position == Vector3.new(0, 5, 0) then
                  -- do something
             end

         end
     end
end

Be sure you aren’t overdoing your line breaks either. Although it is a personal preference on how many line breaks to add, it’s a good idea to use one or two depending on the situation.

Variables

When seeking help from other people, do not name your variables something that is random and irrelevant to your code. In the code sample above, it would be a good idea to not name partA falcon and the other part chicken for no other reason apart from it’s the first thing that pops into your head. It’s also a good idea not do things like a1, b2, c3 to variables that serve some critical function otherwise the person may not remember what a1, b2, or c3 does without having to scroll back. Having simple, descriptive variable names that anyone can understand the purpose of makes it a lot easier when seeking help.

Although this is not much of a problem, and is probably a personal preference by many, keep your variables clustered together and closer to the top of its respective scope. For example, if you’re doing game:GetService() on multiple things like Players, ReplicatedStorage, and ServerStorage within the same script, place them all together near each other at the top. If you have a bunch of variables that have been assigned UI Frames and such, group those together. Don’t scatter variables that are on the file scope (not limited to just one function and can be used anywhere in the script) throughout your code simply because you’re too lazy to scroll to the top and add it there.

Code blocks

Super super super super super important. Code blocks are probably just as important as indentations, if not more important. When use platforms like Discord and Discourse, use three backticks (` not ') to turn your code into a code block. Code blocks, sometimes with highlighting built in, make the code a lot easier on the eyes as there’s a different font and more spacing between characters. Platforms like Discord require you to place a principal file extension (lua, cpp, html) after the first set of backticks for formatting. though Discourse assumes your code blocks to be in Lua. Be sure to look at the preview of your message to make sure your code block didn’t die off in the middle of your code. You can create a code block by placing three backticks(`) before and after the code segment.

Example

```
print(“Hello world!”)
```
would turn into

print("Hello world!")

You can also create inline code blocks by just placing one backtick (`) before and after the code piece. This is useful for formatting short pieces of code that would look obnoxious if they broke a paragraph into bits. For example, I may want to talk about CFrame.new in a paragraph but not want to put it on its own line every time I explain to someone how to use it within the same paragraph.

84 Likes

Thanks for creating this post. I feel that recently new users have not been getting the memo on how to format their code, so I hope this will help them.

11 Likes

Not sure if this is relevant to the original post, but do you think it’s redundant to use comments for services?

For example:

-- Services
local Players = game:GetService("Players")
2 Likes

:eyes:Please stop accessing my code. I don’t think it’s redundant. I think if you’re going to do that, you should at least be consistent throughout your code. This is a sample of what I do:

8 Likes

Excellent. Looks like I can show the newcomers in scripting support if their code formatting is poorly done; hard to read.

Can hardly read their code and thus I had to reformat the code elsewhere for an easier reading.

1 Like

No, it helps with organisational stuff, and helps others read your code

How is your “local” keyword italicized like that?

They probably use VSCode. VSCode has themes that can make certain types of words (for example, local) italic.

So you’re telling me that wasn’t written via Roblox Studio, in a script?

Probably. Some developers use VSCode and things like Rojo to sync scripts into their game. Since VSCode works through the files, people can use tools like git which can be very helpful.

Ah, I get it. I might try this out.

It’s actually a key indicator that whoever is writing that code heavily stresses organization, especially organization that can be followed by others. I do this with ANY script i write. I even include a small header in the first few lines for basic information about the script.

Example Header:

--| ♦ The Force V4
--| ♦ By: TreySoWavvy
--| ♦ 11/18/2022 (Datestamp of original creation.)
--| ♦ Server sided mechanics of the Force system.

Even tho 80% of my scripts are for personal use, I still like to see the various sections in the code and it makes it easier to debug and make changes later on because I’m fully aware how I write code and can jump to various sections quickly and efficiently. Keep doing this :slightly_smiling_face:

1 Like

It’s funny you bring this up almost a year later. I still find myself doing this and I didn’t realize I am always trying to keep myself super organized.

To be honest, I forgot to check the time this thread was made and answered blankly, but it’s good that somebody else does it too!

2 Likes