Menu
Coddy logo textTech

Perimeter Method

Part of the Object Oriented Programming section of Coddy's Lua journey. Lesson 58 of 70.

challenge icon

Challenge

Easy

Let's extend our Shape Manager by adding a :getPerimeter() method to both the Rectangle and Circle classes. Just like :getArea(), each shape calculates its perimeter differently, but they share the same method name—a perfect example of polymorphism in action.

You'll continue working with your existing files:

  • Shape.lua: Your base Shape class remains unchanged.
  • Rectangle.lua: Add a :getPerimeter() method that returns the rectangle's perimeter using the formula 2 × (width + height).
  • Circle.lua: Add a :getPerimeter() method that returns the circle's circumference using the formula 2 × π × radius. Use math.pi for π.
  • main.lua: Require both shape modules, read the dimensions from input, create one Rectangle and one Circle, then print six lines: the rectangle's name, area, and perimeter, followed by the circle's name, area, and perimeter.

Both shapes now have a complete interface with :getName(), :getArea(), and :getPerimeter()—all accessible through the same method names despite different implementations.

Input: Three lines—width (number), height (number), and radius (number).

Output: Six lines in order: rectangle's name, rectangle's area, rectangle's perimeter, circle's name, circle's area, circle's perimeter.

Try it yourself

-- Require the Rectangle module
local Rectangle = require('Rectangle')

-- Require the Circle module
local Circle = require('Circle')

-- Read width and height from input
local width = tonumber(io.read())
local height = tonumber(io.read())
local radius = tonumber(io.read())

-- Create a new Rectangle instance with the given dimensions
local rect = Rectangle:new(width, height)

-- Create a new Circle instance with the given radius
local circ = Circle:new(radius)

-- Print the rectangle's name, area, and perimeter
print(rect:getName())
print(rect:getArea())
print(rect:getPerimeter())

-- Print the circle's name, area, and perimeter
print(circ:getName())
print(circ:getArea())
print(circ:getPerimeter())

All lessons in Object Oriented Programming

Practice on your own: Online Lua compiler