lua-users home
lua-l archive

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


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})
  string.gsub("x", ".", t)

  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"})

  -- It's dangerous for careless sandboxing, too:
  getmetatable("").__index.len = function() print("gotcha!") end