lua-users home
lua-l archive

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


On Mon, 2005-01-31 at 10:59, PA wrote:
> Hello,
> 
> What's the accepted practice to somehow "overload" methods in Lua?

> For example, the following method accepts either a "number" or 
> something else and act accordantly:
> 
>          local function get( anIndex )
>                  if type( anIndex ) ~= "number" then
>                          anIndex = indexOf( anIndex )
>                  end
> 
>                  return ivars[ anIndex ]
>          end
> 
> Is that a reasonable approach? Alternatives?

*F* to 'accepted practices' ":)

Does it work? [yes]

Does it have a problem? Yes -- every new type you add,
you may need to remember to add a case into the function.

Is there a better way?

Sure -- use a statically typed language :)

You can probably arrange a higher level of polymorphism
for *some* functions, by defining them in terms
of other polymorphic functions. EG: lookup
in the argument type metatable.

You can probably arrange 'groups' of types,
to simplify dispatch.

But all these ideas fit into your technique.
They're not alternatives, but refactorings.

Functional composition is the most powerful
technique available.

In fact this is precisely what I suggested for overloading
operator + in Lua. Instead of 'hard coding' the algorithm:

	if type(a) and type(b) are 'number', do number add
	else try meta(a) add method if it exists
	else try meta(b) add method if it exists
	else fail

into the interpreter, which is what is done now,
and is horrid IMHO .. just call a single function.
Which can encode precisely that algorithm .. but
doesn't have to... 

So I think your solution is right because it is most general.

-- 
John Skaller, mailto:skaller@users.sf.net
voice: 061-2-9660-0850, 
snail: PO BOX 401 Glebe NSW 2037 Australia
Checkout the Felix programming language http://felix.sf.net