lua-users home
lua-l archive

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


于 2012-6-16 1:29, Dirk Laurie 写道:
2012/6/15 Stephen Virgo <stephen@creative-assembly.com>:

[...]
The immediate problem can be solved thus: game_wrapper.out = function(self,...) return game:out(...) end But using object-oriented calls is rather pointless if you are going to throw away the implied `self`. So I'd rather do it this way: game_wrapper.out = function(...) return game:out(...) end and call it as my_game.out("This text should appear in the debug console like as if


or you may store the real object somewhere and the __index meta method retrives it and delegate the indexing to it.
for example, you may store the real object in a field of the wrapper object, say, __proto__, the code look like:

----------------- code begin -----------------------

  local game = game_class:new()

  local game_wrapper = {}
  local game_wrapper_mt = {}

  function game_wrapper_mt:__index(key)
    return self.__proto__[key]
  end

  function game_wrapper:new()
    return setmetatable({__proto__ = game}, game_wrapper_mt)
  end

  my_game = game_wrapper:new()

  my_game:out("This text should appear in the debug console like as if I’d called game:out()!")

-------------------- code end ----------------------


another way is to store the map from the wrapper to the real object in an external (weak) table.