lua-users home
lua-l archive

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


Ho,

Or a slightly modified version, where the meta only will be called
the first time the uninitialized value is referenced (but maybe not
assigned to)

-- valid members
vm = { ["top"] = 1, ["left"] = 1, ["bottom"] = 1, ["right"] = 1 }

-- meta table
m = { __index = function( t, k )
	if( vm[ k ] ) then
		rawset( t, k, 0 )
		return 0
	end

	return nil
	end
}

-- the table
t = setmetatable( {}, m )

some_top = t.top + 10
t.top = t.bottom - 45


>table.foreach( t, print )
top		-45
bottom	0

//Andreas

>
> myRet = {}
> setmetatable(myRet,meta_ret);
>
> myRet.top = myRet.top + 10;
>
> print("myRet.top = ",myRet.top);
>
>
> The God's Peace,
>
>
> Leandro.
>
> ----- Original Message -----
> From: "scott" <scott+lua@escherichia.net>
> To: "Lua list" <lua@bazar2.conectiva.com.br>
> Sent: Friday, December 12, 2003 2:37 AM
> Subject: Re: [5.0] trying to auto init a nil field on first ref...
>
>
> > On Thu, Dec 11, 2003 at 08:15:22PM -0800, Ando Sonenblick wrote:
> > >
> > > r = {}
> > > r.top = r.top + 10
> > > print(r.top)
> > >
> >
> > r = {}
> > r.top = (r.top or 0) + 10
> > print(r.top)
> >
> > would give you the results that you are looking for, but forces you to
> > change your second line a bit, which may not be exactly what you wanted.
> >
> > scott
> >
> > --
> >
> >
>
>