lua-users home
lua-l archive

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


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