Writing Clean Code

From Legacy Roblox Wiki
Revision as of 03:59, 10 July 2011 by >ZackZak
Jump to navigationJump to search

--IN PROGRESS--

Introduction

Hey there! I'm going to show you how to write efficient, professional looking code.
It's important to know how to do this, as it will be easier for people to read your code and to debug it. (Not implying your code will have bugs.)

--In case of bugs, call a pest control agency.

Indenting Your Code

One of the most important things to do when writing good code is to indent it.
Indenting may sound like something fancy, but all it really means is that we tab our your functions, if statements, etc.
Here is an example of some messy code that doesn't work due to a missing end that we can't seem to find:

local PowerLevel = -6
function FancyFunction()
PowerLevel = PowerLevel +1
end
for i = 1,10 do
if 1 + 1 == 2 then
FancyFunction()
print(PowerLevel)
end

With indenting we can easily see where our ends meet up, and where there might be a missing one:

local PowerLevel = -6
function FancyFunction()
    PowerLevel = PowerLevel +1
end
for i = 1,10 do
    if 1 + 1 == 2 then
        FancyFunction()
    print(PowerLevel)
end

We can see there that our function ends and for loop ends match up, but our if statement doesn't seem to have one. Then it's a simple matter of adding that in there:

local PowerLevel = -6
function FancyFunction()
    PowerLevel = PowerLevel +1
end
for i = 1,10 do
    if 1 + 1 == 2 then
        FancyFunction()
    end
    print(PowerLevel)
end

Note: Some people think that indenting your code will make it slower, but white space is ignored so you won't notice any difference.

--Now the power level is over 9000! Or.. 4. Same thing.

Good Variable Names

Another important thing to do is to have good variable names.
If you have messy variable names like "mj90_z" it can be confusing for people trying to read your code, it will confuse you if you come back and read it as well as they can be hard to remember.
Here is some code with bad variable names that we can't seem to remember:

epic1337 = false
georgewin = 1
if epic1337 == false then
    georgewin = 0
end

That code wasn't very long, yet it had me confused. I don't know about you though..
I think that code was titled "Get to the chopper script!" but it doesn't seem to make any sense.
We can rename the variables, so it's easier to see what it's doing:

AtChopper = false
PeopleAtChopper = 1
if AtChopper == false then
    PeopleAtChopper = 0
end

Ah. So if you're not at the helicopter the number of people at it is 0. That makes a lot more sense, and now you can understand what's going on.

--In case of helicopter injuries, call that same pest control agency. They have a lawyer division so you can sue me!

Efficiency

If you want to make a big long fancy script, at the same time as conserving time and energy, you'll want to use some of these neat tips.