On 06/07/13 18:52, Tim Hill wrote:
dding nil doesn't change
anything here: your loop would also break if some confused
person stuck a table or a coroutine into the array. It's
already necessary to either check that each value is the
type you expect or ensure that unexpected types don't end up
in the array to begin with, whether nil is an accepted type
or not.
I think this is a fundamental difference.
Array based algorithms (say binary search, some sorting, or
simple traversing) assume that each slot in the array
contains something worth looking up, whatever makes sense
for the application. Nil is never that, because there is
nothing you can do with it. Nil is not something that must
have a meaning in the application domain, it's effectively
out of band application wise.
Not quiet. We're into devious semantics here, but 'nil' can
and does have meaning all over Lua; for example when the
libraries return nil+error message they are using nil to convey
meaning. There are any number of places where you quite
naturally use "if … == nil …". And when you start to work with
generic programming, something that means "not any normal value"
(i'll skip over what "normal" means for the time being), then
'nil' is very valuable. Except you cannot use it in arrays, so
you need a work-around. Hence this entire discussion :)
Well, that's the point: it has a meaning for Lua the language, to
express that there is nothing useful in that place. "nil, error"
expresses just that, "i could not produce any meaningful output, and
here's why". If the language favoured returning nil as a result
equal to, say, a string, then the idiom makes no sense: when the
second return is an error message, and not just a second return?
What i'm trying to say is that in your business logic nil must not
have any extra meaning beyond what Lua gives it ("there is no data
here"). And in that meaning, if I write a buble-sorting library i
expect arrays to be arrays, where every slot is data bound to be
sorted. If i was supposed to support a mythical "array with holes",
i would have to copy all the data to a proper array first! And if
the nil actually get somehow sorted, then it's not a nil, but proper
data, that better have an agreed upon meaning trough all the program
and libraries... The motivation for storing nils in arrays is to
give them a meaning they do not have in the language, and it will
collide with someone else's use, sooner or later.
|