Page 1 of 1

Help with making a class library

Posted: Wed Nov 27, 2019 7:16 am
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?

Re: Help with making a class library

Posted: Wed Nov 27, 2019 9:22 am
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

Re: Help with making a class library

Posted: Wed Nov 27, 2019 3:43 pm
by guy
That actually makes a lot of sense. Thanks for the reply!

Re: Help with making a class library

Posted: Wed Nov 27, 2019 10:48 pm
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