lua-users home
lua-l archive

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

On Fri, Feb 12, 2010 at 2:13 PM, spir <> wrote:
> I'm looking for a way to "subtype" Lua files, for file objects to hold additional attributes. It seems I cannot directly set attributes on Lua Files, since they are userdata. Is there a way to write a custom file type that delegates file methods to an actual Lua file (open in mode 'r')? My trials using __index with a table or function launch errors like:
> lua: _essai.lua:44: calling 'read' on bad self (FILE* expected, got table)
> stack traceback:
>        [C]: in function 'read'
>        _essai.lua:44: in main chunk
>        [C]: ?
> How should I write __index to call a method on a *FILE?

OK, there's always the straight proxy approach:

function wrap(f)
   local obj = {}
   function obj:read(...)
      return f:read(...)
  function obj:close()
  -- etc
  return obj

This gives you a Lua object which delegates the read(),close() etc
methods to the actual file object and gives you an opportunity to add

You can get hold of the metatable used by file objects, as you may
have figured out:

> f = ''
> mt = debug.getmetatable(f)
> = mt
table: 00366C08

So you can add methods, but the 'self' will be the file object.  Then
one can do a closure trick again.

steve d.