[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Metatables are "hard" (Re: Question about __index and classes)
- From: "Dimiter \"malkia\" Stanev" <malkia@...>
- Date: Sun, 28 Aug 2011 13:51:43 -0700
Then we get into __index and __newindex on tables. These only get looked to if the table doesn't contain the key. They are fallbacks for that case rather than overrides for reading or writing tables. As a result, building a structure that catches all reads or writes requires the use of proxy tables and those in turn cause other complications like pairs not working. What's more not containing the key is essentially equivalent to the value being nil, so if you need to build a structure with slots that can contain nil, the structures you need to build to make __index and __newindex work grow more complicated. What's more with both __index and __newindex able to reference tables instead of functions, it is easy to build things that mostly work -- except perhaps for nil values -- and that smell a lot like inheritance in traditional OOP languages.
As lua newbie, I went through the same problem. Now I know one should've
read the book/manual first, before starting with the language, but what
got me into lua was luajit, so I got too excited and skipped them.. I
also got the feeling that the language was small, so I can learn it
iteratively... Few days ago I got the 5.1 book (2nd edition), and gonna
read it tonight on the plane (10+ hour flight + - plenty of time to reread).
What really got me confused about __newindex, __index is that "new"
there - I thought this is only for new indices, so __index should be for
"old", existing keys... But no :)
Maybe __setnewindex and __getnewindex might've been better choice? Not
that these names are any better, except that they both talk about "new"
or non-existing indices... It's not very easy to choose small consistent
names that most people would grok the first time they see them.
The clue was already there though: in the two leading underscores "__" -
that clue kind of made me feel, that something here required some more
detailed knowledge about the language, and it exposes something very
peculiar to it. That's how I got it, so far avoiding the __ (almost no
metatables in my code, but once I get them I'll start using them). My
next attempt was to wrap through luajit the ZeroMQ library more OOP-ish
way - and it failed performance wise (compared to direct FFI "C"-iish way).