Create your own Function Library - Part #3

Hey, it is already Part #3 of our Functions Library. Today we shall look at creating classes, not the ones which you can see are all about setting metatables and creating prototypes, etc. But simple little classes that are self contained. In case you missed Part1 and Part2 ,you can find them here (part1) or here (part2)

Last time in part #2, we saw how to have functions and constants as part of the object returned by a custom library, we shall build on the same principles and create an animal class.

module(...,package.seeall)

 function init(theName, noOfLegs, speakSound)
  local animal = {}
  local name = theName or ""
  local legs = noOfLegs or 4
  local sound = speakSound or ""

  function animal:speak()
   print(name .. " is " .. sound .. "ing")
  end

  function animal:setSound(newSound)
   sound = newSound                                      -- Thanks EugeneS for pointing that out, there was a typo in this line
  end

  function animal:getSound()
    return sound
  end

  function animal:setLegs(newLegs)
   legs = newLegs
  end

  function animal:getLegs()
    return legs
  end

  function animal:setName(newName)
   name = newName
  end

  function animal:getName()
    return name
  end

  return animal
 end

Now to use this object in our app, we can use it as
local animalLib = require("animal")
 
 local dog = animalLib.init("dog",4, "bark")
 local cat = animalLib.init("cat",4, "meow")
dog:speak()
cat:speak()

print("The " .. dog.name() .. " can " .. dog.getSound())
print("The " .. cat.name() .. " can " .. cat.getSound())


If you have a look,, we have kind of repeated every statement, so there is more code than required, specially if there are minimal to no changes. So in optimization we can use,

local animalLib = require("animal")
 
local function createAnimal(name, legs, sound)
  local animal1 = animalLib.init(name, legs,sound)  

  return animal
end

Comments

Popular Posts