lua-users home
lua-l archive

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


Am 18.12.10 10:44, schrieb Drake Wilson:
> 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."  :-)

Indeed, when a new table is created on the hdf object, it's metatable is
set so that I can catch index/newindex.  What I am trying to accomplish
is to access a C datastructure (the HDF containers) using the Lua table
syntax (or at least as close as possible) without having to do deep
copies of the contents of (real) Lua tables.

And it seems that the assignment in the table constructors don't call
newindex, so I end up with a (real) Lua table, but can not access the
values later using my methods.

> 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
>