lua-users home
lua-l archive

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


On Fri, May 1, 2009 at 6:48 PM, Mark Hamburg <mark@grubmah.com> wrote:
> Of course, this then raises the question, why not just name the method
> "stringx_trim" and be done with it:
>
>        S "  test " : stringx_trim() ()
>
> One answer might be that the method chaining wrapper could handle functions
> passed as indices by returning the function itself. Then stringx.trim isn't
> just an identifier for the method, it can actually be the method
> implementation.

The larger issue is that although module writers would like to be as
free and easy to write the most expressive code possible (in this case
having trim() as a string method) it is a problem when these
conveniences impact on global tables like string itself.

Here is another way of thinking about this pattern:

function module_fun (s1, s2)
   s1,s2 = S(s1),S(s2)
   ...
   ... s:trim() etc
end

Here S is a string wrapper which introduces the new methods;
otherwise, S(s) must behave exactly like a Lua string, i.e. it must
understand concatenation, etc. Since its behaviour is a strict subset
of string behaviour, it should be safe to pass to functions expecting
strings - this is probably the hardest thing to get right.

S does double duty, because it can be taught to raise a sensible error
if s1 or s2 were _not_ strings, so one gets argument type checking as
early as possible.

Whether such wrapper methods can be done as efficiently as regular
method lookup, I don't know.  The implementation that comes first to
mind is similar to the sequence adapter pattern I mentioned a few
posts ago.

steve d.