Menu
CoddyTech

Tower Builder

Part of the Roblox Game Scripting section of Coddy's Lua journey. Lesson 7 of 24.

A function is a named piece of code you can run whenever you need it. Values you pass in are called parameters:

local function greet(name)
	print("Welcome, " .. name)
end

greet("Ava")
greet("Leo")

.. joins two strings, so "Welcome, " .. "Ava" is Welcome, Ava. The code prints Welcome, Ava and Welcome, Leo. Defining the function only stores it; each call, like greet("Ava"), runs its code with name set to what you passed.

A function can take several parameters, separated by commas, and use them anywhere inside, like in a Size:

local function makeWall(width, height)
	local wall = Instance.new("Part")
	wall.Size = Vector3.new(width, height, 1)
	wall.Anchored = true
	wall.Parent = workspace
end

makeWall(10, 6)

makeWall(10, 6) sets width to 10 and height to 6, in that order.

A part grows equally up and down from its Position, so a part that is h tall stands on the ground (Y 0) when its center is at h / 2.

challenge icon

Challenge

Easy

Finish makeTower(x, height) and use it three times.

  1. Set the tower's Size to 4 wide, height tall and 4 deep.
  2. Set its Position so it stands on the ground at x: Vector3.new(x, height / 2, 0).
  3. Call it for three towers: (-10, 6), (0, 12) and (10, 18).

Try it yourself

local function makeTower(x, height)
	local tower = Instance.new("Part")
	tower.Name = "Tower"
	tower.Anchored = true
	-- Size: 4 wide, height tall, 4 deep
	-- Position: at x, standing on the ground (center at height / 2)
	tower.Parent = workspace
end

makeTower(-10, 6)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Roblox Game Scripting

Practice on your own: Online Lua compiler