lua-users home
lua-l archive

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


Eike Decker wrote:
"Duck typing is aided by habitually not testing for the type of arguments
in method and function bodies, relying on documentation, clear code, and
testing to ensure correct use. Users of statically typed languages new to
dynamically typed languages may want to add such static, (before
run-time), type checks which defeats duck typing, constraining the
language's dynamism."

I think I'll refer to that page if someone asks me *again* how to
implement static typing in lua.
I was familiar with the term but due to dabbling in Ruby, which I picked after Perl but before Lua. If anyone has Programming in Ruby 2nd ed, it has a whole instructive chapter on duck typing equally applicable to Lua. Here's also, though the language is Ruby, a nice take on various approaches to typing with a dynamic language:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/100511

I used to think for a long long time that somehow inheritance and polymorphism are inherently related. Now I think, in Lua, inheritance from anything is just a form of operator overloading (typically indexing) for tables that happen to be objects or classes. And ducktyping is polymorphism by name, never mind the classes involved. As to inheritance, nothing would stop you from actually copying class data to individual objects, or using closures to build objects. Inside-out-objects and mix-in classes are cool, too, both being easy to implement in Lua.

I can think of two problems with duck typing, which I run into sometimes:

1. Naming. Even if objects would do the same thing, if their authors use a different style of naming methods, they will not be directly compatible without a bit of wrapping or proxying. Examples IsEmpty, empty, is_empty, has_no_elems etc... In a way, one way round it is operator overloading when it makes sense. Relational and arithmetic ops generally have a well defined meaning as does size, indexing and iteration, so such algorithms are likely to do well with duck typing via operator overloading. The empty example could be the test # o == 0.

2. Sometimes the exact interface is not formally specified even in the docs. Meaning that one has to read the code to be able to figure exactly which methods need implementing and which not. Would be nice to be told, OK, these methods got called, so implement at least them.

One solution is a test run with wrapping. Wrap the original class you want to be compatible with. Do some logging before each method when using the original class, by overriding __index, and then delegate to the original. problem solved, now you see exactly which methods are actually needed in an app.

Hth.

--
With kind regards Veli-Pekka Tätilä
Accessibility, Apps and Coding plus Synths and Music:
http://vtatila.kapsi.fi