lua-users home
lua-l archive

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


I don't know if the following idea has already been discussed. At
least I didn't found any reference in the archive.

Currently, in Lua 5.1 and 5.2, tables and full userdata can have an
individual metatable, while other types (number, strings, boolean,
etc) share a single metatable per type.
Type 'string' already has an associated metatable, which is quite
handy since it can enable chained expressions like
str:lower():gsub("1", "2):gsub("foo", "bar").
But because the metatables are global for each type, it is very
dangerous to set them.
Type metatables are nearly unusable in a library, since the library
author cannot assume that the custom metatable won't have side effects
or conflicts in other libraries or user scripts.

My proposal is the following: provided it is possible, why not limit
the metatable scope to the environment of the current function?
Even better, I could imagine that the type metatables could be placed
in the metatable of _ENV and manipulated from there.

Something like this example:

do
local _ENV = setmetatable({}, {
  __boolean = {
    __add = function(a,b) return a or b end,
    __mul = function(a,b) return a and b end },
  __string = {} } )

function f1()
  print(true + false * true) --> true
  print( ("Hello"):lower() ) --> error: attempt to index a string value
end

end -- of custom _ENV

function f2()
  print(true + false * true) --> error: attempt to perform arithmetic
on a boolean value
  print( ("Hello"):lower() ) --> hello
end