[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: PATCH: string.gsub substitution table
- From: Mike Pall <mikelu-0510@...>
- Date: Sun, 16 Oct 2005 15:56:14 +0200
Hi,
Eric Jacobs wrote:
> > }
> > - else { /* is a function */
> > + case LUA_TFUNCTION: {
> > int n;
>
> This condition should be a check on callability, not type; otherwise,
> you break tables/userdata that use __call to do something special.
Well, the original string.gsub never allowed using arbitrary
callables. Look a few lines down in the original code. The patch
only keeps the behaviour. Just try it with plain Lua 5.1-alpha:
local t = setmetatable({}, {__call = function() print("called!") end})
t()
string.gsub("x", ".", t)
called!
lua: bad argument #3 to 'gsub' (string or function expected)
None of the standard library functions that use callbacks allow
arbitrary callables (e.g. table.foreach, coroutine.wrap, ...).
And since the introduction of generic metatables you'd get into
real trouble trying to determine whether an object is callable.
Because you can make strings callable or (if you are brave enough)
even nil!
Generic metatables offer some more surprises:
-- Try to guess what this prints:
local t = setmetatable({}, {__index = "hello world"})
print(t.sub)
-- It's dangerous for careless sandboxing, too:
getmetatable("").__index.len = function() print("gotcha!") end
Bye,
Mike