[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: [5.0] trying to auto init a nil field on first ref... SOLVED!
- From: Ando Sonenblick <ando@...>
- Date: Thu, 11 Dec 2003 20:30:46 -0800
Ahhh... how many times have we all done this... work, try, tweak, ponder, scrunch our faces and then decide to ask the list for help.
Then.... after having spent 10 minutes writing and sending an email, the fog lifts, and voila! the answer appears! Of course it's only AFTER you've already asked for insight... ! :)
Anyway, I came across this solution to my problem:
RectangleMethods =
{
Offset = function(self, x, y) self.top = self.top + y; self.left = self.left + x; end,
}
RectangleMetatable =
{
__index = function(object, key)
local result = RectangleMethods[key]
if result then
return result
end
if not rawget(object, key) then
rawset(object, key, 0)
end
return rawget(object, key)
end
}
r = {}
setmetatable(r, RectangleMetatable)
r:Offset(10, 10)
print(r.left)
I get the correct result of "10" (slightly different than how I posed the question in the first place, but the same net result).
Only drawback to my solution is that any nil field will auto init to 0, but that's acceptable (and faster than special casing top, left, bottom and right)
thx,
ando
On Dec 11, 2003, at 8:15 PM, Ando Sonenblick wrote:
Gang,
I have a table that represents a rectangle. Normally it'd be set up like:
r = {
top = 0
left = 0
right = 100
bottom = 100
}
so that if I then:
r.top = r.top + 10
print(r.top)
I get "10"
What I'd like to do however is have the four fields, if nil when referenced, auto default to zero. I've been trying to get this with __index and __newindex in a metatable, but I can't seem to find a way.
In other words, say I do this:
r = {}
r.top = r.top + 10
print(r.top)
I want want lua to successfully realize that r.top is nil and instead of throwing an error, auto init r.top to zero, add 10 to it, and then print the result
Is this possible? I'm staring to confuse myself now more than gain any clarity....
Thx mucho,
Ando
-----------------------
Ando Sonenblick
SpriTec Software
www.spritec.com
-----------------------
Ando Sonenblick
SpriTec Software
www.spritec.com