34. Services and the data model — Homework solutions
Roblox snippets. The .lua files are in
exercises/34/homework/solutions/.
Problem 1 — Get the services
Worked solution.
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")Grabbing services into locals at the top opens nearly every Roblox script.
Problem 2 — List the players
Worked solution.
local Players = game:GetService("Players")
for _, player in ipairs(Players:GetPlayers()) do
print(player.Name)
endGetPlayers returns a normal list, so the Chapter 22
ipairs loop walks it.
Problem 3 — Server or client?
Sample answer. A Script in
ServerScriptService. A coin that appears for
everyone belongs to the shared world, which only the server
owns. A LocalScript would make the coin on one player's
screen, so nobody else would see it.
Challenge — Count the players
Worked solution.
local Players = game:GetService("Players")
local count = 0
for _, player in ipairs(Players:GetPlayers()) do
count = count + 1
end
print(count .. " players connected")The Chapter 20 count pattern, on the player list.
(#Players:GetPlayers() gives the number directly too.)
Done?
You can find any service and know where your code should live. The book's last chapter — leaderstats and value objects — uses them to build the score display every Roblox game has.