Page 1 of 1

Creating classes/modules

Posted: Fri Dec 02, 2016 11:30 pm
by jonathancyu
How would I create classes and modules? I've been using tables in the main file to use for classes but there has to be a better way (requiring classes in the folder?)

Re: Creating classes/modules

Posted: Sat Dec 03, 2016 5:54 am
by raidho36
Lua only has tables so no, you will always wind up using tables. Having enough dedication, you can do it via closures but you really shouldn't.

Lua doesn't have classes so regardless of the way you do it, it's fine - as long as you don't do anything absurd, of course. Conventional way is to create a table that has a number of functions attached to it, which represents class, and to create an instance of the class you create a new table and assign class table as its metatable, i.e.

Code: Select all

local instance = setmetatable ( { }, Class )
It's a common practice to put that in a "new" method of a class and then return the instance from it.

As for modules, since certain Lua version the way you do it is by defining a (local) master table in a file, and at the end of the file returning that table. All functions, variables and constants go into that table. You can, of course, use locals there.

Code: Select all

local module = { }
function module.foo ( )
  return bar
end
return module
Then you can require that file as a module.

Re: Creating classes/modules

Posted: Sat Dec 03, 2016 7:05 am
by zorg
For libs/modules, this is a neat read in my opinion: http://kiki.to/blog/2014/03/30/a-guide- ... a-modules/
But basically, what raidho said above.

Re: Creating classes/modules

Posted: Sat Dec 03, 2016 8:34 am
by Tjakka5
If you dont want to use libraries, here's 2 ways of doing it.

Code: Select all

local Class = {}
Class.x = 0
Class.y = 0

function Class.new(x, y)
   local object = {
      x = x,
      y = y,
   }

   return setmetatable(object, {
      __index = Class
   })
end

function Class:getPosition()
   return self.x, self.y
end

return setmetatable(Class, {
  __call = function(_, ...) return new(...) end
})
Or

Code: Select all

local function getPosition(self)
   return self.x, self.y
end

local function new(x, y)
   return {
      x = x or 0,
      y = y or 0,

      getPosition = getPosition
   }
end

return setmetatable({
   new = new,
   getPosition = getPosition
}, {
   __call = function(_, ...) return new(...) end
})