lua-users home
lua-l archive

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


Am 21.12.2013 18:00 schröbte Dirk Laurie:
2013/12/21 Sir Pogsalot <sir.pogsalot@gmail.com>:
On Fri, Dec 20, 2013 at 2:04 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:

2013/12/20 Sir Pogsalot <sir.pogsalot@gmail.com>:

3) I'm missing something obvious that makes this a bad idea.
+1

The following pieces of code so the same.

setmetatable(a,{__pairs=tbl})
for k,v in pairs(a) do print(k,v) end
for k,v in pairs(tbl) do print(k,v) end


Hmm, I do not understand why that is bad

Because it is not unreasonable to expect that when one
does `for k,v in pairs(a) do`, `v` will be a value from `a`.
The metamethod might supply some cases where `v` is
nil, it might ignore some key-value pairs, but if you deny
me the comfort of the assertion `a[k]==v`, I will be lost.

You can have your comfort back by means of an `__index` metamethod. I sometimes use this pattern in my code (e.g. [1]). I'm not sure though if this proposal is worth the effort, it only saves three lines of code in a very special case, and since `__pairs` is called only once per for-loop there is no obvious performance advantage either.

Philipp


[1]: https://github.com/siffiejoe/lua-class/blob/master/src/class.lua#L111