lua-users home
lua-l archive

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



On Mon, Apr 14, 2014 at 7:21 PM, Coroutines <coroutines@gmail.com> wrote:
On Mon, Apr 14, 2014 at 9:10 AM, Aapo Talvensaari
<aapo.talvensaari@gmail.com> wrote:
> I wish that there was a way to monkeypatch variables with monkeypatching
> scope limited.
>

You could do much of this with proxy tables

I know that, but proxying strings to proxy tables means that they are not strings anymore. Compare that to string.myfunction = function(self) end (now every string has "myfunction" but they still are plain strings, e.g. type returns "string"). This is what I'm after. To patch that function to all the strings that are used this point forward, but patches released after this scope ends (e.g. no global changes, only local string changes).

local str = "example"

local function test(str)
    -- this only affects to local scope
    setlocalmetatable(string, { __index = { myfunction = function(self) end }})
    -- this works now:
    str:myfunction()
end

test(str)

-- this doesn't work anymore:
str:myfunction()


Regards
Aapo