lua-users home
lua-l archive

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


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.

> [...]
> 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.:

> 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?

If you must do so, just hard-code the keys (they're already hard-coded into
the C struct), unless there are really a lot of them, in which case either
you should use some dynamic data-structure in C other than a struct (which
will then allow iteration over its keys), or use a code-generator (e.g. cpp)
to generate both the struct and the list of keys, forcing them to remain in
sync and effectively providing a limited form of introspection in C.

-- David