lua-users home
lua-l archive

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

It was thus said that the Great David Favro once stated:
> On 02/02/2012 05:53 AM, Dimitris Papavasiliou wrote:
> > [...]
> > struct {
> >    int a;
> >    char *b;
> > } foo;
> > 
> > If you want to get/set the members of this struct from Lua you need to
> > set up an empty table with a metatable having __index and __newindex
> > metamethods like so:
> Or you could just expose it as a full userdata, with metatable which
> provides access to the members.

  That's what I do.

> > [...]
> > The code is more or less arbitrary of course and might be buggy but
> > it's just meant as an illustration.  The problem is now that doing:
> > 
> > for k, v in pairs (fooproxy) do
> >    print (k, v)
> > end
> Is it really useful that pairs() functionality be emulated for such a
> struct?  I know that was just an example, but how many elements will it
> have?  I don't think most people would bother implementing pairs() even in
> 5.2 -- e.g.:

  I know I would love to have pairs() work on a fulluserdata---it would make
debugging easier (code that can dump a Lua table would also work on

> > for k,v in pairs(io.stdout) do print(k,v) end
> stdin:1: bad argument #1 to 'pairs' (table expected, got userdata)
> After all, the C-struct-as-a-Lua-table paradigm only works to a limited
> extent -- are you going to allow insertion of new keys via __newindex?

  *Raises hand*  At work, I wrote a testing harness and as part of that
harness I need to create a bunch of datafiles, some of which are in a custom
key/value file format.  I provide a fulluserdata with both __index and
__newindex methods to retrieve/store records into these key/value stores.  I
also support both integer and string based keys (since the key/value store
can also be accessed as an array).

  But even if you aren't going to add new keys, it's still advisable to set
__newindex to allow the setting of existing fields in a