[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Alternative (better?) __index implementation
- From: "Thomas Lefort" <thomas.lefort@...>
- Date: Tue, 27 Nov 2007 10:19:19 +0100
On Nov 27, 2007 2:50 AM, alex.mania@iinet.net.au
<alex.mania@iinet.net.au> wrote:
> Hey,
>
> First time poster here.. be gentle.
>
> For a particular oo system I was experimenting with, I found the current __index
> metamethod to not work quite as desired. The difference is best explained through
> an example:
>
> local proxy = setmetatable({}, {__index = function(tab) return tab.greeting end})
> local test = setmetatable({ greeting = "hello" }, {__index = proxy})
> print(test.unknownkey)
>
> The current implementation would print nil,
Or maybe:
lua: tmp/index.lua:1: C stack overflow
stack traceback:
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
tmp/index.lua:1: in function <tmp/index.lua:1>
...
You can guess why. Next time test your code before you post ;-)
> I propose it would be more meaningful
> for the end __index metamethod to be called with the table that instigated the
> __index loop, rather than table that holds the function. The performance
> difference is negligible, and the change can be implemented with one line of code
> and one changed variable name.
Yes, I found myself wishing for this at some point too, but it can
still be emulated with adequate metamethods. Even if this can get a
bit heavy (very relative when doing Lua anyway) I believe it should be
preferred over a semantic change in the language core.
--
-- Thomas