[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Overloading and extending operators
- From: Mike Pall <mikelu-0704@...>
- Date: Wed, 11 Apr 2007 17:28:26 +0200
Hi,
Joe Krahn wrote:
> Is anyone else thinking about or working on something like this?
I posted some ideas about this, inside some other discussion on
efficiency:
http://lua-users.org/lists/lua-l/2006-09/msg01019.html
BTW: If you don't care too much about efficiency then check out
this simple hack:
local sm = setmetatable
local function infix(f)
local mt = { __sub = function(self, b) return f(self[1], b) end }
return sm({}, { __sub = function(a, _) return sm({ a }, mt) end })
end
Now you can define your own named infix operators:
local shl = infix(function(a, b) return a*(2^b) end)
print(5 -shl- 4)
--> 80
Cute, huh? Advantage: no changes to the Lua core needed.
Drawback: one table allocation per operation.
[Credits: this mimicks a similar Python hack:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
]
Bye,
Mike