[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: implicit conversions in Lua -- what is idiomatic?
- From: Josh Haberman <jhaberman@...>
- Date: Mon, 6 Jan 2014 09:37:00 -0800
On Mon, Jan 6, 2014 at 4:47 AM, Fabien <fleutot+lua@gmail.com> wrote:
> I personally find that the subtle bugs it creates aren't worth the
> convenience, especially for string->number.
>
> However, the "proper" answer depends on your audience:
>
> If you target people who will write complex code and maintain it durably, I
> think you don't want unnecessary magic that helps them lose track of their
> types.
This is definitely the direction I am leaning. My preference is to
throw an error if the user assigns anything that the type can't
represent exactly.
I even want to throw in the struct.age = 22.12345 case (because I
can't represent the decimal digits), but since this is contrary to the
behavior of luaL_checkinteger() I started to worry that I was going
down a path that is contrary to the expectations of Lua users.
To give a bit more context, what I am working on isn't a binding of a
specific C data structure, but a full Protocol Buffer library. So in
reality my example would look more like this:
-- Define the type in Lua (could also load it from a .proto file instead).
person_msgdef = upb.build_defs{
upb.MessageDef{
full_name = "Person",
fields = {
upb.FieldDef{name = "name", number = 1, type = upb.TYPE_INT32},
upb.FieldDef{name = "age", number = 2, type = upb.TYPE_STRING}
}
}
}
-- Create an instance of this type.
person = upb.Message(person_msgdef)
person.name = "James"
person.age = 22
serialized = upb.pb.Serialize(person)
Checking overflow/truncation/etc. seems very important because it
affects whether the user's data will actually make it into the
serialized form or not.
To answer Andrew's point:
> Having C code throw an error if I add a non-existent field is
> very un-Lua like. In fact, it might be you that wants to
> extend the struct and finds that it's easier to build the nice
> interface in Lua, instead of C.
I think I have this covered, because the schema can be
defined/extended in Lua, so if the user wants to extend the struct
they just extend the schema.