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.lua

 

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:createCatalog()

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

               return o

end

 

function MyClass:createCatalog()

 

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

                                                            return x*2;

               end

 

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

               return x*y;

               end

 

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

               return x/y;

               end

end

 

MyClassUser.lua

 

 

require("MyClass")

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"

4

6

0.66666666666667

 

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

 

2017-03-19 1:50 GMT+02:00 Marcello Chiuminatto <mchiuminatto@gmail.com>:

 

> 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)](...)

end