lua-users home
lua-l archive

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


2009/12/16 steve donovan <steve.j.donovan@gmail.com>:
> On Wed, Dec 16, 2009 at 5:45 PM, Alexander Gladysh <agladysh@gmail.com> wrote:
>> I'm for a metatable on string module's table — to catch __index and
>> __newindex access and fail with meaningful runtime error.
>
> That would be easy. It's already an error to try set a new key using a
> string, just need the __index fallback further up.
>
> 'Overloading the index operator' for strings is a one of those cool
> tricks that enact a penalty, The first is that __index becomes a
> function that has to check the type of the key, and that means that
> any string method access is slightly slower, but the one that is hard
> to quantify is loss of type specificity; strings become 'indexable'
> but they are not tables.  Initially I was fond of overloading __call
> for strings so that s(3) was equivalent to s:sub(3,3) and s(3,5) was
> equivalent to s:sub(3,5). But then all my strings were callable, and
> mostly they were not meant to be callables!  So error messages get
> more obscure if you pass a string to something expecting a function.

This is a design decision in Lua programming that I've been faced with
several time, whether you should accept indexables and callables, or
tables and functions. First it's easy to check for a value type, but
it's harder to determine if it's callable or indexable in pure Lua.
Second it's easy to wrap a callable or an indexable in a closure or a
proxy table respectively. So maybe forcing argument types rather than
accepting any object might be a better choice in general (maybe with
an exception for booleans).