lua-users home
lua-l archive

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


I like to use the structs provided by the ffi from luajit (I believe it can be used as an external module in normal lua).  They are real C structs in the backend and as such are much easier on the system resource-wise.  You can even have real typed arrays with any custom struct you want. See the example on C data structures at http://luajit.org/ext_ffi.html


On Mon, Nov 19, 2012 at 7:09 AM, steve donovan <steve.j.donovan@gmail.com> wrote:
On Fri, Nov 16, 2012 at 12:39 PM, spir <denis.spir@gmail.com> wrote:
> local Contact = Record{"phone","email","address"}

Latest version of the 'strict struct' pattern described in the wiki
can now also support this constructor form.

But you have to define it as an ordered map:

struct.Contact {
   {phone = 0},
   {email = 'text'},
   {address = 'text'}
}

foo = Contact(2344344,'foo@bar.org','blah blah')  -- note not using
table ctor here!

There is also an option to use proxy tables, in which case you can
catch type errors on field assignment.

BTW, I'm using a somewhat generalized version of type() here - see the
function _type in the code, exported as struct.type. This returns
_name field of the metatable if it exists.

The values of the keys (whether the keys are ordered or not) serve a
double purpose: providing sensible defaults, and type checking. It
would be a good idea to extend the concept of type matching as Geoff
has suggested so that we can insist that a value is a number between 1
and 10, or a string matching some pattern.

I am not happy about one thing - currently it exports the struct names
into the global table.  I'm starting to think that this is a mistake,
even though a redundant syntax 'Foo = struct.Foo{...}' becomes
necessary if one wants Structs with Names.

Have a look at test-struct.lua for an executable manual ;)

https://gist.github.com/4110502

steve d.