lua-users home
lua-l archive

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


You can do this with generalized 'for' construct in Lua 5. All you have to do is to write a function that generates 'next' pair the way *you* want it. For instance, one could write a generator function that iterates through every sub-entry within a given table hierarchy or only some designated entries satisfying some criteria. In your case, the criteria would be to pay attention to "__index" and include those into your iteration domain. No new metamethods are needed for this.

Alex  

> -----Original Message-----
> From: John Passaniti [mailto:jpass@rochester.rr.com]
> Sent: Thursday, March 06, 2003 2:10 PM
> To: Multiple recipients of list
> Subject: Enumerating Inherited Properties
> 
> 
> Here's something that's come up in some code I'm writing.
> 
> Let's say I have a table with some interesting data in it:
> 
> 	Parent = {this=1, that=2}
> 
> Now let's use Lua 5.0's nifty "easy inheritance" and create a Child
> table that inherits from the Parent:
> 
> 	Child = {other=3}
> 	setmetatable(Child, {__index = Parent})
> 
> Which lets you do this:
> 
> 	print(Child.this, Child.that, Child.other)
> 
> Giving the expected result:
> 
> 	1		2		3
> 
> Now let's iterate over the keys in Child:
> 
> 	table.foreach(Child, print)
> 
> We get:
> 
> 	other		3
> 
> And that makes sense.  After all, the Child table does really 
> only have
> one key in it.  But what if that's not what you want?  What 
> if you want
> to iterate through both the real and inherited keys in Child without
> regard to if they were in Child or Parent (or a parent of 
> Parent, etc.)?
> 
> Does anyone have an elegant way to deal with this?  
> 
> (Maybe this suggests a new metamethod?  One way this could work is if
> tables had a metamethod related to indexing a table.  Such a 
> metamethod
> would have application beyond this message's example.)
> 
> 
> 
>