How to keep your code dry

  • Don't

    1. Functions

    Functions are containers of reusable code.

    Say you want to print the squares of certain numbers.

    You might write it like so;

    for i = 1, 10 do

    But what if you need to do this multiple times? Don't copy and paste the same exact code.

    Instead, put it in a function.

    local function printSquares(start, goal)
        -- printSquares is just a variable that contains a reference to this function 
        start = goal == nil and 1 or start
        for i = start, goal do
    printSquares(5); -- instead of copying the body, just copy this call with any numbers 

    2. Variables

    If you will often be using something, it's best to have a variable contain it/a reference to it.

    Like you might want to change a parts properties.

    game.Workspace.Part.Transparency = 0.2;
    game.Workspace.Part.Reflectance = 0.2;
    game.Workspace.Part.BrickColor ="Really red");

    Instead have a variable refer to the part!

    local part = game.Workspace.Part
    part.Transparency = 0.2;
    part.Reflectance = 0.2;
    part.BrickColor ="Really red");

    But actually use part! There's many cases where one declares a variable, but never uses it and just indexes the game and its descendants until a certain child is reached, despite having a variable for it

    3. Loops

    Say you want to do something a certain amount of times, it would be tedious to just copy the code the amount of times you want to do something, that is where loops come in.

    -- Instead of manually calling printSquares 10 times
    for i = 1, 10 do
        printSquares(i, i);
    -- And if you want to do something forever
    while true do
        part.BrickColor = BrickColor.Random();

  • @sjr04Alt bad code

  • good code

  • how to do code blocks in forum

  • @ArtyomAL3X you do

    like this

  • Can definitely agree that people need to be thoughtful of this. Often times when I am proof checking someone else's code, its usually very repetitive and could be simplified a lot.

    Always make sure you actually understand the code you write and proof check it. Also important to write it in such a way that it is efficient in run time as well as not repetitive.

Log in to reply

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.