lua-users home
lua-l archive

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


On 06/07/13 09:20, Rena wrote:
For case 1, the "problem" is that setting a field to nil removes it. This seems to be quite rarely an actual problem, and only crops up when you're reading data from an external source (such as a database) where "nil" doesn't mean "this field does not exist" like it does in Lua, *and* you need to iterate all of the fields without knowing their names in advance.

...
Anyway, in that situation, there's another solution that nobody seems to have brought up: eliminate the "names not known in advance" issue by getting a list of names. e.g. instead of your database query returning a table like:
{{id=1, name="Joe", gender='M'},
{id=2, name="Jean, gender='F'},
{id=3, name="Sam", gender=nil}}
have it structured like:
{columns={'id', 'name', 'gender'},
{1, "Joe", 'M'},
{2, "Jean", 'F'},
{3, "Sam", nil}}


I think this is extremely sensible. If your field can exist separately from the data, store them separately.

It does seem awfully strange to me: Lua's strings can contain any byte, because they store the length separately from the string data. This is generally considered a good thing, especially compared to C strings - it takes length lookup from O(n) to O(1) and allows them to contain arbitrary binary data. Yet Lua's arrays don't have this same feature, and instead use the C-string method of a magic terminating value that can't appear anywhere in the array, which limits what they can store.

This I'm not so sure. Strings store their length, true, but that's just an implementation detail: at any position they store something: a char. There are no holes in strings.

Now, when using pairs or ipairs I always get something. The implication of holes is that when I iterate, I would have to check for nil at every step. That would just seem wrong to me: in my mind, an array does not have holes, just as strings don't.

nil is a very strong language level concept. From the language level, at every position in a array you have something. If the index exists, there must be something there. And nil is not "something", it means "this does not exist"

Jorge