lua-users home
lua-l archive

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


Lua is very flexible! You can achieve this behavior easily:

meta = {__index = {top = 0, bottom = 0, left = 0, rigth = 0}}
r = setmetatable({}, meta)

print(r.top)
r.top = r.top + 10
print(r.top)

Milano

From: Ando Sonenblick <ando@spritec.com>
Reply-To: Lua list <lua@bazar2.conectiva.com.br>
To: Lua list <lua@bazar2.conectiva.com.br>
Subject: [5.0] trying to auto init a nil field on first ref...
Date: Thu, 11 Dec 2003 20:15:22 -0800

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


_________________________________________________________________
MSN Hotmail, o maior webmail do Brasil.  http://www.hotmail.com