[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lists with nil play nice for Lua 5.2
- From: David Given <dg@...>
- Date: Sun, 29 Jul 2007 21:12:57 +0100
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Asko Kauppi wrote:
> I agree with John about the annoyance of this non-intuitive nil
> handling. And I do my set of tricks around it, as John pointed many of
> us do...
I don't like it, either. I'm just not sure this can be easily fixed without
changing a fundamental core semantic.
Having the array operators fail when applied to invalid tables is certainly
one way around this, but I'm not sure if it can be done efficiently ---
wouldn't checking a table for valid array-ness require looking at every
numeric element in the table? This is potentially useful in a hypothetical
strict mode (I'd certainly use it!), but I wouldn't want it all the time. (I
can also think of a fairly straightforward approach for efficiently ensuring
that #t on a hole-y array becomes deterministic and is always the index
immediately preceding the first unused slot, which is another approach.)
This also doesn't help John's original problem in that he wants to be able to
use nil as a valid element in an array. I'm not sure this can be achieved
without changing the behaviour of table in a non-backward-compatible way.
Given an array {[1]=1, [2]=2, [3]=nil, [4]=4}, then does ipairs() visit
element 3 or not? If it *does*, it's violating table behaviour; if it
*doesn't*, it's violating (the desired) array behaviour.
Given that it's fairly trivial to construct an efficient Array 'class' with
specific array semantics, I'd be rather inclined not to risk changing anything:
function Array(...)
local data = {...}
local length = select(..., "#")
local o = {
...accessor functions here...
}
setmetable(o, o)
return o
end
That way you get a nice OO interface that conforms to ideal semantics for
arrays, and you're not forced into backwards compatibility with tables.
Alternatively, simply don't use nils to mean 'unset' --- it's trivial to
create a value specifically for doing this ('unset = {}'). After all, if it
hurts when you do this, don't do this...
- --
┌── dg@cowlark.com ─── http://www.cowlark.com ───────────────────
│
│ "There does not now, nor will there ever, exist a programming language in
│ which it is the least bit hard to write bad programs." --- Flon's Axiom
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFGrPTIf9E0noFvlzgRAsTXAJ95W8JVOkctlm/Vn5QPbbK659evSACgsn6r
G70NG4EnG2OgpWAKHYl5jSc=
=750M
-----END PGP SIGNATURE-----