lua-users home
lua-l archive

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


Changing the meta table of string is OK for the one main application,
but a no-go for any library, or a script among several possible
equals.
One can argue if ("hallo")[2] should return "a" or 97. I personally as
Dirk here would tend to the second. But I believe this ambiguousity
might be exactly the reason why Lua does so far not provide that
default __index for strings.

On Sun, Dec 19, 2010 at 10:19 PM, Matthew Wild <mwild1@gmail.com> wrote:
> On 19 December 2010 20:37, Lucas Zawacki <lfzawacki@gmail.com> wrote:
>> I don't know if this would be regarded as a "good practice" but  you
>> could just use metatables to create a __call method for strings and
>> make it behave like string.byte does. Therefore you can:
>>
>> local mah_string = "hello"
>> print( mah_string(1) )
>>
>> I would provide an example but a quick search in the manual (I'm quite
>> new to lua...) has led me to this:
>>
>> "You can replace the metatable of tables through the setmetatable
>> function. You cannot change the metatable of other types from Lua
>> (except by using the debug library); you must use the C API for that."
>>
>> And I suck at using the C API so I'll just leave the idea here. Please
>> correct me if I'm wrong and  it's not possible to use metatables for
>> that purpose :)
>>
>
> It's possible. What's more strings already have a metatable that you
> can modify in Lua, so no need to change which metatable strings use
> (that could only be done from C, or using debug.setmetatable() ). e.g.
> getmetatable("").__call = ...
>
> Matthew
>
>