Class Models for Lua

# Object Wrapper

## `loop.object.Wrapper`

Class of objects that create a wrapper around an object using an efficient delegation model that allows execution of delegated methods with the state of the delegated object, i.e. by replacing the `self` parameter. This class is useful to implement wrappers that overwrites some of the operations of a object.

Each wrapper may provide specific methods that are executed with the wrapper object as the `self` reference. However, when a method is called that is not provided by the wrapper and but is provided by the wrapped object then a special method is used that replaces the `self` reference by the wrapped object. Only one single special method is used to perform the `self` replacement for all delegated methods of all wrappers without creating temporary closures or any other kind of structure. However, this mechanisms only work for method calls done with the `:` operator.

## Behavior

### Fields

`__object`
  Object the missing methods are delegated to. The prefix `__` is used to avoid name colisions.

### Meta-Fields

`__index`
  Setup the special delegation method in order to delegate the execution of the method indexed to the object defined by field `__object`.

## Remarks

- Only one single Lua function is used to perform the delegation of all methods indexed in every `Wrapper` instance. Therefore all indexed methods that are not provided by the `Wrapper` instance itself are the same function no matter if they are actually delegations of different methods.
- The `:` operator guarantees that the method index and execution is an atomic operation thus it is guaranteed that the setup performed by meta-method `__index` on the delegation function is preserved until the delegation method execution. If the method index and execution are not performed atomically the results are unpredictable because the delegation function settings may change by another method invocation.

## Examples

### File handler that adds line breaks to strings written.

    local Wrapper = require "loop.object.Wrapper"

    file = Wrapper{ __object = assert(io.open("desc.txt", "w")) }

    function file:write(text)
      return self.__object:write(text, "\n")
    end

    file:write("This text is being written into a file with a method")
    file:write("redefined by a wrapper that adds line breaks to the ")
    file:write("strings written. However this file will be closed by")
    file:write("a method delegated to the original 'userdata' object")
    file:write("that represents the file handler. Since the 'close' ")
    file:write("method of Lua file handlers do not expect to receive")
    file:write("the wrapper object as the 'self' parameter, it must ")
    file:write("be replaced by the original 'userdata' object.")

    file:close()

Copyright (C) 2004-2008 Tecgraf, PUC-Rio

This project is currently being maintained by Tecgraf at PUC-Rio.