[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...
- From: "Leandro Candido" <enclle@...>
- Date: Fri, 12 Dec 2003 09:45:15 -0200
Hello All,
Your version, more compact yet ;-):
r = setmetatable( {}, { __index = { top = 0, bottom = 0, left = 0, right
= 0 } } )
--...--
The God's Peace,
Leandro.
----- Original Message -----
From: "Milano Carvalho" <milanogc@hotmail.com>
To: <lua@bazar2.conectiva.com.br>
Sent: Friday, December 12, 2003 8:56 AM
Subject: RE: [5.0] trying to auto init a nil field on first ref...
> 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
>
>