lua-users home
lua-l archive

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


On 25 June 2015 at 03:52, Tim Hill <drtimhill@gmail.com> wrote:
>
>> On Jun 23, 2015, at 4:46 PM, Daurnimator <quae@daurnimator.com> wrote:
>>
>> As I replied on IRC; I think that lexically scoped metatables for the
>> base types are a much better idea.
>> I even coded up a proof of concept:
>> https://gist.github.com/daurnimator/dedd793e6f9b1f8d6b0c
>> (obviously if such a feature made it into PUC-lua, the `debug` calls
>> would be unnessecary)
>>
>
> I’m scratching my head on the utility of something like this.

It means you can add new string methods for use inside a library, but
not have them leak all over the place.
e.g. some theoretical module might really like a `split` method.

local _ENV = {string=setmetatable({}, {__index=_ENV.string })
function string:split(c) ...... end

local function bar(s)
    local t = s:split("/')
    return t[2]
end
return {
    bar = bar;
}

Similarly it allows the creation of a sandbox that can interact with
normal lua code.
(usually for a sandbox you need to lock down the string metatable, or
else a user can DoS via time consuming string operations)

> Besides, if you want it, then the existing _ENV mechanism can do this for you. Just wrap the type in a metatable (a trivial bit of C code) and have it’s metamethods defer to functions in the current environment.

The thing is you want to avoid wrapping primitives just for use in
your libraries; it would involve all sorts of pack/unpacking.
Especially once you bring callbacks or coroutines into the story.

> This is really the beauty of Lua; it’s meta-language model that provides the facilities whereby YOU can easily add these features without having to encumber the base language.

Not so much with this case.
There is only one string metatable.
This means that it has to be shared by *all* code/libraries in a given
lua state.
Which means that all good libraries should consider it read-only.