[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A guide to building Lua modules
- From: steve donovan <steve.j.donovan@...>
- Date: Tue, 15 Apr 2014 10:41:57 +0200
On Tue, Apr 15, 2014 at 12:00 AM, Enrique Garcia Cota <kikito@gmail.com> wrote:
> So instead of deciding, I looked at how the language does things. As you
> say, you can monkeypatch `type` if you want, and you'll face the
> consequences.
I'm sympathetic to the urge; common strategy is for custom type() to
respect __type. Beyond that, everyone and their dog has their own
ideas about what an extended Lua type is. The main thing is that this
new type() should behave exactly like the old one, in the absence of
__type.
Although Lua is a dynamic language, we reason about code in a static
way. If I see table.insert and it does not behave like the
table.insert in the manual, then that's going to blow my programs out
of the water. Here there is no need to overload the standard function
with new meanings.
A module writer has to respect the global namespace, but is free to do
any funny stuff within the module. Some resources are (currently)
global, like the metatables associated with strings or functions.
Sometimes we'd like to go a little wild, e.g. add new functions to
string so we get new methods, and that's fine - in a program. (For
instance, pl.stringx provides new string functions, but
stringx.import() has to be called explicitly to move these into global
string)
I've played with giving functions a metatable so I can define
composition and partial application as operators, but I can't
recommend the practice - there's nearly always another way of doing
this - like wrapping functions in a object with __call, and defining
the operators on that wrapper[1]
One of the advantages of the somewhat tedious practice of defining all
imports as locals up-front is that it's defensive programming, just in
case someone got clever[2] with a basic function. But it seems
unfortunate that one has to be defensive about such really basic
things...
[1] you do pay a bit for the extra abstraction, although less than you
think. If there's the proverbial tight inner loop, then a good
abstraction can be temporarily hoisted....
[2] oh yes, we've all been there! But increasingly I feel cleverness
should be in overall design, not in implementation.