lua-users home
lua-l archive

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


It was thus said that the Great Marcello Chiuminatto once stated:
> Hi everybody
> 
> Maybe someone can help with this.
> 
> I have "polymorphism" situation where I want to define a function that
> depending on a condition will have different signature and behaviors
> 
> I would like something like this, but unfortunately does not work. Is
> there any other way to implement this in lua?
> 
> MyClass = {
> }
> 
> If somecondition == 1 then
>   MyClass.f = function (self, x)
>                return x*2 
>   end
> end
> 
> if somecondition == 2 then
>   MyClass.f = function (self, x,y)
>                return x*y
>   end
> end
> 
> if somecondition == 3 then 
>   -- this case escapes from polymorphism since have the same signature
>   -- that f in somecondition == 2, but I need this anyway.
> 
>   MyClass.f = function (self, x,y)
>                return x/1
>   end
> end

  What do you mean by "does not work"?  What error are you seeing?  Because
from what I can see, this will work (you can always pass more parameters
than a Lua function expects---said function will just ignore the extra
parameters).  

  -spc