lua-users home
lua-l archive

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


Hello,

-- as I also need to solve this --

another (simplified) example:

----
local mt =
{ __index =
  { --a = "aaa",
  },
  --function(t, k) print("mt", t, k) end
}

local mt2 =
{ __index =
  --{ a = "AAA",
  --},
  function(ttt, k) print("mt2", ttt, k) end -- [1]
}

setmetatable(mt.__index, mt2)

local t = setmetatable({}, mt)

print(t, mt, mt.__index, mt2, mt2.__index, t.a)
----

yields:

----
C:\Lukas>Test.lua
mt2     table: 003CB108 a
table: 003CB4A0 table: 003CAD50 table: 003CB108 table: 003CB430 function: 003CB480      nil
----

Function [1] receives 'mt2.__index' as 'ttt' argument ('table: 003CB108'), which is in agreement with Lua manual but is a bit useless when we are operating with table 't' (or - in another case it may be userdata).

So, question: how to (anyhow) pass the table 't' to the function [1] so that be able to access 't' members?
Which skill/trick/algorithm to use here?

Best regards,

Lukas



On Wed, 22 Oct 2014 01:54:28 +0200, Philipp Janda <siffiejoe@gmx.net> wrote:

Am 21.10.2014 um 19:11 schröbte Andre Arpin:
This post is long so I remove all quotes
Note: the unexpected value of self when o.baz is invoked.

This is exactly the same problem as before: `o:baz()` involves two
distinct operations: one `__index` call to retrieve the `baz` function,
and finally one call to that `baz` function. The `__index` function and
the `baz` function may (and in this case will) be called with different
`self` arguments. You are trying to do all the work in the `__index`
function alone:


setmetatable(getmetatable(metainstance.__index).__index, {
         __index = function(self, key)

This `self` is always the same as
`getmetatable(metainstance.__index).__index`, *not* `o`.

             print(self, key, "self, key")
             dump(self, 'self')
             for k,v in pairs(self) do
             	print(k, v, 'k,v')
             end
             if key == "baz" then
                 print(type(self), (self).v)
                 return rawget(self,'v')

Here you are trying to access `o` (the object before the colon operator
in `o:baz()`), but it is simply not available here. You have to return a
function reference at this point, which in turn will be called with the
`self` value you expect (i.e. `o`).

             end
         end,
     })


Philipp






--
Ing. Lukáš Procházka | mailto:LPr@pontex.cz
Pontex s. r. o.      | mailto:pontex@pontex.cz | http://www.pontex.cz
Bezová 1658
147 14 Praha 4

Tel: +420 241 096 751
Fax: +420 244 461 038