lua-users home
lua-l archive

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


On Mon, Dec 13, 2010 at 2:36 PM, Enrico Colombini <erix@erix.it> wrote:
> By the way, I'm not advocating any change to the current #t implementation,
> just writing for the sake of discussion, which could perhaps lead to
> interesting ideas for a future Lua version.

Absolutely. What worries me is that arrays can develop _accidental_
holes and this tends to mess with people's minds.

local append = table.insert
local T = {}
for _,o in ipairs(names) do
   append(T,find_object(name))
end

find_object() may return nil, which is a standard Lua way of saying
'sorry chum no can do', and the fun begins.

(BTW, this loop is often packaged as 'map' - so a hidden requirement
of any such function is that the mapped function should not return
nil.)

One approach is 'fail early and fail noisily'

local function append(t,s)
   if s == nil then error('cannot add nil to an array!") end
   t[#t + 1] = s
end

Or use a sentinel:

null = {}

local function append(t,s)
   t[#t + 1] = s==nil and null or s
end

(It would be possible to write a variant of ipairs() which then
converted null to nil when iterating.)

Another idea is that we could arrange null (through suitable change to
the core) to have the following properties (a) it is a unique value
(b) type(null) == 'nil'.

table.insert() would covert nils to nulls, and so forth.

steve d.