lua-users home
lua-l archive

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


On Wed, May 6, 2009 at 3:47 AM, David Manura <dm.lua@math2.org> wrote:
> but we must not carelessly pass the wrapped object to functions
> outside of the lexical scope expecting a string.  We cannot guarantee
> that our wrapper behaves exactly like a string because Lua strings are
> not fully virtualizable [2].

Absolutely; no way to make duck-typing seamless with built-in types.
One would need a corresponding 'unwrap' function U when calling
routines from other modules, which would become tedious, although
again U can do duty as a type assertion.

> An alternate idea is to modify the string metatable to be scope aware:

Definitely the cool idea of the week!  But there would naturally be a
practical concern with the runtime cost, especially since the debug
library is used.

The Metalua solution is indeed very elegant. Since Metalua operates
with the AST  of the source, it may be possible to rewrite expressions
like:

    s:upper():trim()

into:

   stringx.trim(s.upper())

A smart implementation would also create local aliases into the module
scope, so the resulting code becomes truly optimal:

function trim_upper(s)
    return s:trim():upper()
end

becomes

local trim,upper = stringx.trim, string.upper

function trim_upper()
   return upper(trim(s))
end

Then our cost happens at compile-time, which may be a good tradeoff.

Fabien, is this kind of thing possible with Metalua?  I guess one
would need some kind of static type annotation to give enough clues to
the compiler, however.

steve d.