Modules in Lua

Developers that have tried objective-C or Java have quit and looked for alternatives. This is where a lot of new frameworks offering LUA have emerged, these frameworks are all fine, each competing with the easy and each having it's niche. Here is an article on how to use Modules in LUA which can be used in any of the frameworks that you so choose.

This Post has information that can be used generically and therefor used by developers on Gideros or CoronaSDK. so here goes - How to create Modules.

1. What is a Module
Think of a Module as a Library, a collection of functions that can be in their own self and be used by various apps if you include these modules.

2. How do I create a Module?
A module file contains the functions that you want to use, so for this scenario, we shall create two functions called new and myprint

--[[
filename:test.lua
--]]

 function new()
   local object={}
   return object
 end

 function myprint(theObject)
  print("The object is ", theObject)
 end


Now this module can be easily called from the main.lua file as
--[[
filename : main.lua
--]]

 require("test")

 a = new()
 myprint(a)

this whould work on Gideros without any issues, but on CoronaSDK, you have to just add the line

module(...,package.seeall)

I have yet to try out Moai in detail, but since this is how LUA works rather than any of the frameworks, this should work across any framework that uses LUA, even WAX.

This is fine, but sometimes as a developer one might want to create an object, metatables, etc there are plenty of examples that complicate things. How about a simple way?

--[[
 filename : test.lua
--]]

 function newOO()
  local object={}
  
  function object.print(self)
    print("Hello from ", self)
  end

  return object
 end

and the main.lua file would call it as

b = newOO()
 b:print()

 print(b)

so this should be a good start to understand how one can create objects with LUA.

Comments

Popular Posts