Create your own Function Library - Part #2

Hope you did enjoy the first part and learn a few things about using Lua Libraries. In Part 1 , we saw how to declare a library in Lua. Now let us look at creating slightly advance libraries that encompass their own functions.

Advanced Return Types
We have returned primitives in the last series from our functions, such as

  module(..., package.seeall)

  function oneString()
    return "one"
  end

  function oneInt()
    return 1
  end

Now, the advanced version of this could be

 module(...,package.seeall)

 function init()
  local returnObj = {}

    function returnObj:oneString()
     return "one"
    end

    function returnObj:oneInt()
     return 1
    end

  return returnObj
 end

With this new library file, the way to access our functions will also change. Here's how to use such a library

  local myFunc = require("library").init()
  
  print(myFunc:oneString())

  print(myFunc:oneInt())


With this new way to define, we can also have constants and members from the library that can be used.

 module(...,package.seeall)

 function init()
  local result = {
     ONE = 1,
     TWO = 2,
     THREE=3,
   }
  return result
 end

Now to use it,

  local myFunc = require("library").init()
  
  print(myFunc.ONE)
  print(myFunc.TWO)


So we just saw how to have functions and members from a library handle. So let's make a test library for our custom math library.

 module(..., package.seeall)

 function init()
   result =
   {
     DEBUG = false,
     ONE = "one",
     TWO = "two",
     THREE="three"
   }
   
   function result:add(a,b)
     return a+b
   end

   function result:sub(a,b)
     return a-b
   end

   return result
 end

 function description()
  print("This is a custom math library")
 end


Hope you have gotten an idea of how it all fits together and how a library of functions can be used to provide a set of functions that are part of an object.

In part 3 we shall look at furthering this concept to classes and objects.

As usual cheques and comments are welcome ;)

Comments

Popular Posts