[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Custom "comparison for equality" in Lua ?
- From: "Wim Couwenberg" <w.couwenberg@...>
- Date: Fri, 3 Jan 2003 11:28:54 +0100
Hi,
> How can I let the lua interpreter make :
[... snip snip ...]
> if a==b then print("equality") end
>
> run as expected (i.e. print "equality") ?
In Lua 4 there is no tagmethod to redefine ~= or ==. Instead, you can write
(in)equality functions or member functions, like:
function equal(c1, c2)
return c1.r == c2.r and c1.i == c2.i
end
etc.
A nice way to implement member functions in general is by redefining the
"index" event like so:
local complex_tag = newtag()
local complex_meta = {} -- shared members of complex type go here
settagmethod(complex_tag, "index", function(_, index) return
%complex_meta[index] end)
function complex_meta:equal(other)
return self.r == other.r and self.i == other.i
end
-- a simpleton complex number constructor...
function complex(r, i)
local c = {r=r, i=i}
settag(c, %complex_tag)
return c
end
c1 = complex(1,2)
c2 = complex(1,2)
-- test for equality
if c1:equal(c2) then print "equal!" end
Hope this helps,
Wim