lua-users home
lua-l archive

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

My approach was wrong, because I was trying to assign the function at loading time (upon require execution) when what I really needed was that the function assignment was in a object by object basis.  This post opened my eyes and finally I found a solution. Thanks, this will save me a lot of lines and ifs when using the module.




MyClass = {

                              myType = "",

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

                              myVar =0


function MyClass:new (type)

               o =  {}   -- create object if user does not provide one

               setmetatable(o, self)

               self.__index = self


               o.f = self.myCatalog[type].f

               return o



function MyClass:createCatalog()


               self.myCatalog["type1"]["f"] = function(self, x)

                                                            return x*2;



               self.myCatalog["type2"]["f"] = function(self, x, y)

               return x*y;



               self.myCatalog["type3"]["f"] = function(self, x, y)

               return x/y;








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))


>lua -e "io.stdout:setvbuf 'no'" "MyClassUser.lua"





-----Original Message-----
From: [] On Behalf Of Dirk Laurie
Sent: Sunday, March 19, 2017 3:20 AM
To: Lua mailing list <>
Subject: Re: Conditional Function Definition


2017-03-19 1:50 GMT+02:00 Marcello Chiuminatto <>:


> I have “polymorphism” situation where I want to define a function that

> depending on a condition will have different signature and behaviors


Lua has many mechanisms for polymorphism, but none of them work exactly as in C++, since the type of a Lua value at runtime can be anything.


Your code does not work because it tests the function condition at compile time (i.e. only one of the forms of MyClass.f get compiled) whereas true polymorphism requires that the results depend on what arguments you pass. In C terms, you are in effect using #ifdef.


Here for example is a function polymorphic on the number of arguments.


morphs = {math.exp,math.log,math.max}


function poly1(...)

   return morphs[math.min(select('#',...),3)](...)