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

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-RioThis project is currently being maintained by Tecgraf at PUC-Rio.