lua-users home
lua-l archive

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


2016-03-14 22:32 GMT+02:00 Sean Conner <sean@conman.org>:

>   My initial reaction was "Gaaaaah!  Nooooooo!" but upon further reflection,
> this might be okay.  You could change the names of the metamethods:
>
>         mt.+ = function(a,b) ... end            -- __add


$ lua -l ihelp -l redefine
Lua 5.3.2  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> ihelp(redefine)
--- redefine(prototype,symbol,method)
-- redefine(tbl,'+',myplus) etc
>

It should be blindingly obvious how to code "redefine", but for those
who love the idea, a start is provided in the attachment. Come to
think of it, something like it is probably already in some utility package.
-- redefine.lua  © Dirk Laurie 2016  License: WTFPL
-- This is just a stub. Write the rest of it yourself.

local synonym = {
  ['+'] = "__add";
  ['<'] = "__lt";
  ['..'] = "__concat";
}

--- redefine(prototype,symbol,method)
-- redefine(tbl,'+',myplus) etc
return function(prototype,symbol,method)
  local mt = getmetatable(prototype)
  if not mt then 
    mt = {}
    debug.setmetatable(prototype,mt)
  end
  if type(mt)~='table' then return end
  symbol = synonym[symbol] or symbol
  mt[symbol] = method
end

--[[
function vec_lt(a,b)
  local i=1
  while a[i]~=nil and a[i]==b[i] do i=i+1 end
  return a[i]~=nil and b[i]~=nil and a[i]<b[i]
end
]]