35. leaderstats and value objects — Homework solutions
Roblox snippets. The .lua files are in
exercises/35/homework/solutions/.
Problem 1 — A points value
Worked solution.
local points = Instance.new("IntValue")
points.Name = "Points"
points.Value = 0An IntValue holds one whole number in
.Value.
Problem 2 — leaderstats on join
Worked solution.
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local wins = Instance.new("IntValue")
wins.Name = "Wins"
wins.Value = 0
wins.Parent = leaderstats
end)The folder must be named exactly leaderstats;
Wins becomes the column.
Problem 3 — Add a win
Worked solution.
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
local wins = leaderstats:FindFirstChild("Wins")
if wins then
wins.Value = wins.Value + 1
end
endEach FindFirstChild is guarded with if, so
a missing folder or value never crashes.
Challenge — Two stats
Worked solution.
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Value = 0
coins.Parent = leaderstats
local rank = Instance.new("StringValue")
rank.Name = "Rank"
rank.Value = "Novice"
rank.Parent = leaderstats
end)Both value objects sit in the same leaderstats folder,
so the leaderboard shows two columns, Coins and
Rank.
Done?
That is the whole book. You can install Lua, write and run programs, make decisions and loops, build data with tables, organise code with functions, modules, and classes, and carry it all into Roblox Studio through Instances, events, services, and leaderstats. The final two mini-projects — Touch-to-Collect Coin and Collect-All-Coins — pull the Roblox half into playable scenes. Good luck with the games; the terminal is here whenever you need it.