lua-users home
lua-l archive

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


On Wed, Dec 4, 2013 at 4:23 PM, Marc Lepage <mlepage@antimeta.com> wrote:
> Say I am writing C code that wants to get and set properties with string
> values, the equivalent of:
>
>     obj1.foo = 'optionA'
>     obj2.foo = 'optionB'
>     print(obj3.foo)
>
> where in the C code, the strings like 'optionA' must be converted to values
> like ENUM_A. Typically, for a property I might have up to half a dozen
> values.
>
> So for setting a property, I could manually get the argument as a string,
> and use strcmp to choose which enum value is being specified.
>
> Or, I could just build a table where keys are strings and values are the
> enum values, and use that to lookup which enum value is being specified.
>
> Which is generally preferred? Is there a better way?
>
This is a great question. I'm interested in the answers that you get,
because I've done about ".8" of a binding, although I've refactored it
twice and may go for a third.

My experience:

I started with `char lua_name[][64 = {"friendly_name", "next_name", ...}`

which either matched and enum or matched an integer array that held
the constants. (the latter being what's needed in nanomsg, given that
there are holes everywhere.)

This seemed messy, so I made a struct. The struct then lead to me
making a more full-on association that generalized properties. Now I
have an array of stuff like this:

const struct property properties [] = {
   {"linger", NN_SOL_SOCKET, NN_LINGER, &def_linger, sizeof(def_linger )},
   ...
}

But all of this was necessary because I am doing (probably) too much
in C and not enough in lua.

Anyway, would love to hear how others approach this.

-Andrew