lua-users home
lua-l archive

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


On Mon, Jun 21, 2021 at 1:48 PM Soni "They/Them" L. wrote:

local _GETNAME = function(o, k)
  if type(o) == "table" and k == "insert" then return table.insert end
  return o[k]
end

This allows doing t:insert(foo) on any table t.


Found one more example:

I want to replace the standard string method
   s:gsub(pattern, repl [, n])
with my customized variant
   s:gsub(pattern, repl [, n] [, plain])
So, I redefine string.gsub
But it does not have any effect under a sandbox because strings' metatable is global, I have just my private copy of _ENV.string.


Indeed, if we can redefine accessing global variables locally in runtime (due to _ENV), why not having the same feature for other actions?

I'd like to have two special optional fields inside _ENV table: _NEWTABLE and _INDEX

_NEWTABLE would keep a function invoked automatically as the final step of creating a table from a table constructor.
For example, the statement
   x = {1, 2, 3}
would silently act like
   x = _ENV._NEWTABLE{1, 2, 3}

"__index" metamethods for "type-shared metatables" are better to make local (per chunk) instead of global (per VM) and make accessible without the debug library.
"Type-shared metatables" are: the metatables for strings/numbers/functions, and highly requested shared metatable for all metatable-less tables.
_ENV._INDEX would keep local versions of "__index" metamethod for "type-shared metatables".
For example, local redefinition of gsub would look like
   _ENV._INDEX.string = setmetatable({gsub = mygsub}, {__index = _ENV._INDEX.string})
And this is how Soni can use t:insert() for any table inside his module:
   _ENV._INDEX.table = _ENV.table