lua-users home
lua-l archive

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


2015-09-22 18:18 GMT+02:00 Scott Morgan <blumf@blueyonder.co.uk>:
> On 22/09/15 16:50, Javier Guerra Giraldez wrote:
>> __newindex is a fallback, not an override.  that means that it's only
>> called when the table doesn't have that index already.  that is, when
>> it's a new index.
>>
>> if you want to get all settings, you do a "proxy table", i.e. don't
>> store in the object table itself, but on an different, internal table.
>
> Ah, I follow, knew I was missing something simple. Misunderstood
> newindex. Proxy tables for general stuff like this.
>
> Would this also work for globals? Copy the contents of _G (using Lua 5.1
> in this example) into a private table, nil out _G's entries and set it's
> metatable to reference the private table.

In 5.2/5.3, rather do this in a script [1]:

_ENV=setmetatable({},{__index=_G})

This give you full flexibility. You can make the original
value inaccessible (assign something to `_G.whatever`)
or keep it lurking in the wings (assign something to `whatever`,
thus changing _ENV.whatever but not affecting _G.whatever.).

[1] It does not work that way in an interactive session: what you do
to _ENV on a line then only remains in effect until the end of that
line (or group of lines if you entered a multiline chunk).