Coin Factory
Part of the Roblox Game Scripting section of Coddy's Lua journey. Lesson 8 of 25.
A table holds a list of values in curly braces, and a for loop can visit each one:
local heights = { 4, 8, 12 }
for _, h in heights do
print(h)
endThis prints 4, 8 and 12. Each round, h holds the next value. The _ is the position in the list, which this loop does not need.
Combine a table with a function and you get a factory: one call per value.
local function makeTree(x)
-- build a tree at x
end
for _, x in { -10, 0, 10 } do
makeTree(x)
endCanCollide = false lets players walk through a part; it is still there and still visible.
A Folder groups parts, like workspace.Coins. Setting a part's Parent to a folder puts it in the world inside that folder.
Challenge
EasyFinish the coin factory: makeCoin(z) builds one gold coin, and a loop calls it for every number in spots.
- In
makeCoin, addcoin.CanCollide = falseandcoin.Anchored = true. - Add
coin.Position = Vector3.new(0, 3, z), thencoin.Parent = workspace.Coins. - Below the function:
for _, z in spots do makeCoin(z) end.
Press Play: five gold coins float in a line. Then Check.
Try it yourself
local spots = { 12, 6, 0, -6, -12 }
local function makeCoin(z)
local coin = Instance.new("Part")
coin.Name = "Coin"
coin.Shape = Enum.PartType.Ball
coin.Size = Vector3.new(2, 2, 2)
coin.Color = Color3.fromRGB(255, 200, 40)
-- 1. Walk-through and anchored
-- 2. Position at (0, 3, z), then put it in workspace.Coins
end
-- 3. Call makeCoin for every spot
All lessons in Roblox Game Scripting
2Loops and Functions
Row of PillarsStaircase BuilderTower BuilderCoin FactoryBlinking LightVanishing Bridge5Your First Game
Your First ObbyPractice on your own: Online Lua compiler