Help with making a class library

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
guy
Prole
Posts: 11
Joined: Wed Sep 19, 2018 7:10 pm

Help with making a class library

Post by guy »

I just started getting back into Lua and I decided to try and write my own class library based on ones made by other people (rxi and recursor specifically). So far I have this:

Code: Select all

local Class = {}
Class.__index = Class

function Class:new()
  local obj = setmetatable({}, self)
  obj['__call'] = self.__call
  obj.__index = obj
  return obj
end

function Class:__call(...)
  local obj = setmetatable({}, self)
  obj:load(...)
  return obj
end

return Class
But from looking at the implementations of the people mentioned above, they have something like this in Class:new() as well as an initialization function at the top of the file with nothing in it.

Code: Select all

function Class:new()
  local obj = {}
  obj['__call'] = self.__call
  obj.__index = obj
  setmetatable(obj, self)
  return obj
end
So what's the difference between the two? And why would you need an empty initialization function?
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Help with making a class library

Post by ivan »

Have not tested your code but it looks fine. I would set the metatable last:

Code: Select all

function Class:new()
  local obj = {}
  obj.__index = obj
  return setmetatable(obj, self)
end
This should prevent bugs if you are doing something weird in the parent class metamethods
User avatar
guy
Prole
Posts: 11
Joined: Wed Sep 19, 2018 7:10 pm

Re: Help with making a class library

Post by guy »

That actually makes a lot of sense. Thanks for the reply!
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Help with making a class library

Post by raidho36 »

Take a look at my class library. It has all the basic features, some additional stuff, and can bind FFI datatypes to classes.
https://bitbucket.org/rcoaxil/lua-minil ... /class.lua
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Amazon [Bot], Bing [Bot], Google [Bot] and 9 guests