lua-users home
lua-l archive

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

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

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

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