Read a messy script, spot the smells, and restructure it in small safe steps until the code matches the plan — without changing a single pixel of gameplay.
Debugging taught you how to read an error and trace back to the code that caused it. That's much easier when the code between errors is worth reading. Refactoring is the skill of cleaning up working code — renaming, extracting, flattening — without changing what the experiences. It never adds a feature and never fixes a bug; it only makes the next feature and the next bug easier to deal with.
A refactor changes how the code is written, never what it does. The clicking the coin sees the same +10. The server still saves the same wallet. Only the shape of the Luau underneath is different — and that difference is the whole point: code that's easy to read is code that's easy to change without breaking.
Three rules make a refactor safe:
if. Never try to "fix the whole " in a single edit.Which of these is a good, safe refactor?
Here is the new- setup handler from the Coin Tycoon's first messy version. It works — every gets stats, some gifts, and their saved coins back. But it smells:
local Players = game:GetService("Players")
local CoinStore = require(game.ServerStorage.CoinStore)
Players.PlayerAdded:Connect(function(p)
local s = p:WaitForChild("leaderstats")
local c = Instance.new("IntValue")
c.Name = "Coins"
c.Value = 0
c.Parent = s
if p.UserId == 0000000 then -- special dev reward
c.Value = 99999
end
local x = 1
while x <= 3 do
local gift = Instance.new("IntValue")
gift.Name = "Gift" .. x
gift.Value = 10 * x
gift.Parent = s
x += 1
end
if p:GetAttribute("returning") then
local d = CoinStore:Load(p.UserId)
if d.Coins ~= nil then
if d.Coins > 0 then
if d.Coins < 10000 then
c.Value = d.Coins
else
c.Value = 10000
end
end
end
end
end)
The five smells:
p, s, c, x, d — none of them say what they hold. Reading this is decoding, not reading.99999, 3, 10, 10000 appear out of nowhere. Where does 10000 come from? Why is it in two places?ifs deep. The else c.Value = 10000 at the bottom belongs to an if three levels up — easy to misread, easy to misindent.10000 cap is spelled twice — once in the , once in the assignment. Two copies of one rule is two chances to update only one of them.Which smell makes the restore block hardest to reason about?
We'll fix every one of these, in order, one small step at a time.
First pass: make the names say what they hold — p becomes player, s becomes stats, c becomes coins, d becomes saved. Renaming is the cheapest refactor and the most underrated: it converts three-letter hieroglyphs into prose you can read on Monday morning.
While renaming x, notice what it really is: a counter that starts at 1, bumps on every trip, and stops at 3. Luau already has a shape for "count from 1 to 3" that needs no mutable counter at all:
for giftIndex = 1, 3 do
local gift = Instance.new("IntValue")
gift.Name = "Gift" .. giftIndex
gift.Value = 10 * giftIndex
gift.Parent = stats
end
x was unnecessary state — a you changed to drive a . The for hands giftIndex to each trip ready-made, so the counter disappears entirely. Less state means fewer things that can drift out of sync.
local x = 1
while x <= 3 do
local gift = Instance.new("IntValue")
gift.Name = "Gift" .. x
gift.Value = 10 * x
gift.Parent = s
x += 1
end
Replace the manual counter with a for loop that names its index.
Renamed, the same block reads like the plan: "for each of the three gifts, make an IntValue named GiftN worth 10 times its number, place it in the stats."
10000 floats in the middle of the restore block. 3 only makes sense next to the gifts. The 99999 dev reward looks like a typo. Magic values are decisions hidden in arithmetic — and decisions belong at the top of the where they can be seen, changed, and named:
local GIFT_COUNT = 3 -- one value, one place
local GIFT_VALUE = 10
local MAX_COINS = 10000
local DEV_REWARD = 99999 -- the dev account's hello balance
local DEV_USER_ID = 0 -- the developer's player id
Now the code can say what it means instead of reciting a number:
for giftIndex = 1, GIFT_COUNT do
gift.Value = GIFT_VALUE * giftIndex
end
And the cap gets its second pass: the rule "never restore more than the cap, never set a balance below zero" is one line with math.min and math.max — which also deletes the duplicated 10000 and the > 0 check, because a clamped value can never be negative:
coins.Value = math.max(0, math.min(saved.Coins, MAX_COINS))
Using the named constants, write the single line that restores saved coins clamped between 0 and MAX_COINS.
-- constants live at the top of the script
local MAX_COINS = 10000
-- inside the restore block, saved.Coins was just loaded
if saved.Coins then
coins.Value = -- cap the restored amount, never negative
endThe restore block is still four ifs deep. Deep nesting isn't just ugly — it's expensive to read: every if adds a branch you have to track, and the real action hides at the bottom. The fix is another cheap, powerful pattern: guard clauses.
A guard clause checks a early and returns. Instead of wrapping the entire restore in if player:GetAttribute("returning") then, we bail out when the isn't returning:
if player:GetAttribute("returning") ~= true then
return
end
local saved = CoinStore:Load(player.UserId)
if not saved.Coins then
return
end
coins.Value = math.max(0, math.min(saved.Coins, MAX_COINS))
Three flat lines instead of a pyramid. Each guard answers one question — "are they returning?", "did they save anything?" — and leaves the code after it able to assume the answer is "yes". Four levels of if became zero.
Last smell: one PlayerAdded handler doing four jobs. The fix is extracting — moving each job into its own named so the handler becomes a of contents:
local function createStats(player)
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Value = 0
coins.Parent = player:WaitForChild("leaderstats")
return coins
end
local function applySpawnGifts(stats)
for giftIndex = 1, GIFT_COUNT do
local gift = Instance.new("IntValue")
gift.Name = "Gift" .. giftIndex
gift.Value = GIFT_VALUE * giftIndex
gift.Parent = stats
end
end
local function restoreCoins(coins, player)
if player:GetAttribute("returning") ~= true then return end
local saved = CoinStore:Load(player.UserId)
if not saved.Coins then return end
coins.Value = math.max(0, math.min(saved.Coins, MAX_COINS))
end
Players.PlayerAdded:Connect(function(player)
local coins = createStats(player)
applySpawnGifts(coins.Parent)
if player.UserId == DEV_USER_ID then
coins.Value = DEV_REWARD
end
restoreCoins(coins, player)
end)
The handler is now four lines of "what happens", and each how lives in a small with a name. Want to change the gift pattern? applySpawnGifts. Curious how savings get restored? restoreCoins. You never read forty lines to answer a two-line question again.
The damage math from the sword fight works, but it was written in a hurry. Clean it up: give the parameters real names, rewrite it readably, and introduce a named MINIMUM_DAMAGE constant. Do not change how it calculates — the checks expect identical results. Keep the function name damage so the checks can find it.
Hint: A headshot doubles, a block halves, and the result never drops below 1 — those three rules must survive the cleanup.
Renaming the parameters, clearing the clutter, and extracting the constant was the whole game — the outcome stayed identical while the code became something you'd actually enjoy opening. That is the refactor in miniature.
This is why testing matters so much: once refactors get bigger than one , "I ran it and it felt fine" stops being enough. Testing fundamentals is next — turning 'same game, cleaner code' from a hope into a machine-checked claim.
Next up: Testing Fundamentals — claims that prove code works, in a form the computer can verify on every single run.