lua-users home
lua-l archive

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


On Mon, May 4, 2015 at 7:56 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2015-05-03 23:39 GMT+02:00 Nagaev Boris <bnagaev@gmail.com>:
>> On Sun, May 3, 2015 at 8:38 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>>> 2015-05-03 21:24 GMT+02:00 Andrew Starks <andrew.starks@trms.com>:
>>>
>>>> I could not bare to triple post, and this idea is different enough
>>>> that I'll take the opportunity to fork...
>>>>
>>>> sand boxing the string's metamethods is something that would be nice
>>>> to be able to do, but it is hard to imagine that feature existing
>>>> without something being treated as "special".
>>>>
>>>> I don't know if this mechanism would be general and useful enough for
>>>> consideration, but I did think of a way that I believe could be used
>>>> to solve this problem.
>>>
>>> It is trivial to sandbox a string's methods.
>>>
>>> ---
>>> $ lua
>>> Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
>>>> getmetatable"".__metatable = "Sandboxed!"
>>>> string = nil
>>>> str = "The quick brown fox"
>>>> for k in str:gmatch"%S+" do print(k) end
>>> The
>>> quick
>>> brown
>>> fox
>>
>> This is exactly what I want to prevent.
>
> So do this:
>
> local orig_gsub = string.gsub
> my_safe_gsub= function(str,patt,repl)
>    if type(repl)~="string" then error"This gsub allows only string
> replacement" end
>    return orig_gsub(str,patt,repl)
> end
>
> safe_string_library = { find=string.find, sub=string.sub, gsub=safe_gsub,
>    match = string.match, gmatch = string.gmatch }  -- or whatever
>
> debug.setmetatable("",{__index = safe_string_library, __metatable="Sandboxed!"})
> string = safe_string_library
>

Thank you, Dirk and Sean!

I overlooked debug.setmetatable("", ...)



-- 


Best regards,
Boris Nagaev