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