lua-users home
lua-l archive

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


Quoth Marc Balmer <marc@msys.ch>, on 2010-12-18 10:16:53 +0100:
> The Lua code puts in a loop database results in a HDF container:
> 
> 	hdf.bset = {}
> 	for n = 1, res:ntuples() do
> 		hdf.bset[n] = {}
> 		hdf.bset[n].id = res:getvalue(n, 1)
> 		hdf.bset[n].name = res:getvalue(n, 2)
> 		hdf.bset[n].description = res:getvalue(n, 3)
> 	end
> 
> And as LHF pointed out, Lua wise the following snipped should be equivalent:
> 
> 	hdf.bset = {}
> 	for n = 1, res:ntuples() do
> 		hdf.bset[n] = {
> 			id = res:getvalue(n, 1),
> 			name = res:getvalue(n, 2),
> 			description = res:getvalue(n, 3)
> 		}
> 	end

Only "equivalent" semantically, and only if the tables aren't too
magical.  I get the feeling you're resetting the metatables of new
tables when they come in, which would make these decidedly magic
tables.  "A wizard did it."  :-)

The former snippet refetches the ['bset'] and [n] parts each time,
which is only completely equivalent if you get out exactly the value
you put in, which looks to not be the case here.  Certainly they're
not guaranteed to have exactly the same performance or internal
implementation characteristics regardless.

I'm guessing you're assuming you can do some internal bookkeeping with
associating new keys using only newindex.  If you're going to allow
the latter style of assignment you need to iterate any incoming tables
the first time you see them.  And if you're actually reusing the
tables but setting new metatables on them (as opposed to making a deep
copy of all the data inside), this is kind of dangerous, at least if
you don't check that there's no original metatable first.

   ---> Drake Wilson