lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, Mar 19, 2017 at 5:35 AM, Marcello Chiuminatto
<mchiuminatto@gmail.com> wrote:
> function MyClass:new (type)
>                o =  {}   -- create object if user does not provide one
>                setmetatable(o, self)
>                self.__index = self
>                o:createCatalog()
>                o.f = self.myCatalog[type].f
>                return o
> end


Hello Marcello,

You probably want "local o = {}".  Otherwise o will be global.
(Welcome to Lua.)

Also, your comment "create object if user does not provide one" is
incorrect.  "o = {}" will always create a new table and assign it to
the global variable o.  There is no way, in your MyClass:new function,
for the user to provide an object.

Also, every time you call MyClass:new, you will call createCatalog.
This means every time you create a new object, you will also create 3
new functions.  For each object after the first object, these three
functions will be redundant.  This is inefficient.

If you have not read Programming in Lua, I recommend it.  Especially
the chapter on metatables:

http://www.lua.org/pil/contents.html#13


-- Here is your code, rewritten to be IMO (minimally?) correct.

MyClass  =  {
  myType     =  "",
  myCatalog  =  {  type1={}, type2={}, type3={},  },
  myVar      =  0 }

MyClass.myCatalog.type1.__index  =  MyClass.myCatalog.type1
MyClass.myCatalog.type2.__index  =  MyClass.myCatalog.type2
MyClass.myCatalog.type3.__index  =  MyClass.myCatalog.type3

function MyClass.myCatalog.type1:f ( x, y )  return x+2  end
function MyClass.myCatalog.type2:f ( x, y )  return x*y  end
function MyClass.myCatalog.type3:f ( x, y )  return x/y  end

function MyClass:new (type)
  local o  =  {}   -- create new object
  setmetatable ( o, self.myCatalog[type] )
  --  o.f  =  self.myCatalog[type].f    -- unnecessary and probably incorrect
  return o
end

local obj1 = MyClass:new("type1");
local obj2 = MyClass:new("type2");
local obj3 = MyClass:new("type3");

print (obj1:f(2))
print (obj2:f(2,3))
print (obj3:f(2,3))


-- Here is how I would rewrite the same code from scratch.

type1, type2, type3  =  {}, {}, {}

type1.__index  =  type1
type2.__index  =  type2
type3.__index  =  type3

function type1 : f (x, y)  return x*2  end
function type2 : f (x, y)  return x*y  end
function type3 : f (x, y)  return x/y  end

local obj1  =  setmetatable ( {}, type1 )
local obj2  =  setmetatable ( {}, type2 )
local obj3  =  setmetatable ( {}, type3 )

print ( obj1 : f ( 2, 3 ) )
print ( obj2 : f ( 2, 3 ) )
print ( obj3 : f ( 2, 3 ) )


Cheers,

Parke