lua-users home
lua-l archive

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



-----Original Message----- 
> From: "Roberto Ierusalimschy" <roberto@inf.puc-rio.br> 
> To: "Lua mailing list" <lua-l@lists.lua.org> 
> Date: 02-07-2013 20:58 
> Subject: Re: new "empty" value/type in Lua? 
> 
> 
> Is something like this enough? (Note that 'n' is *not* hidden; I do
> not think hidden stuff is good in the end...)
> 
> -- Roberto
> 
> ------------------------------------------------------------------------
> -- Module 'array'
> -- (tested lightly :)
> 
> local type, floor, pack, setmetatable, rawset =
>   type, math.floor, table.pack, setmetatable, rawset
> 
> _ENV = nil
> 
> local array = {}
> 
> local nexti = function (t,i)
>   i = i + 1
>   if i <= t.n then
>     return i, t[i]
>   end
> end
> 
> 
> local mt = {
>   __len = function (t) return t.n end,
> 
>   __newindex = function (t,k,v)
>     if type(k) == "number" and k == floor(k) and k > t.n then
>       t.n = k
>     end
>     return rawset(t,k,v)
>   end,
> 
>   __ipairs = function (t) return nexti, t, 0 end
> }
> 
> mt.__index = array
> 
> 
> function array.new (...)
>   local a = pack(...)
>   setmetatable(a, mt)
>   return a
> end
> 
> 
> function array.setlength (t, n)
>   if n < t.n then
>     for i = n + 1, t.n do t[i] = nil end
>   end
>   t.n = n
> end
> 
> 
> return array

Still looks like the best of the 3 options suggested. I don't see why a new type should be introduced for if this could be a solution, neither an empty type nor a special container type seem appropriate. The only thing that people may don't like is, it needs a metatable. table.pack already reintroduced the 'n' so this speaks actually for of using it.

But I would like to hear Tim's opinion if this would solve his problem. I suppose it only helps him if this would be the 'official' way to store lists with nils.

Just two thoughts:

- If n is public, setlength() is not needed at all, but it's a nice function that helps the user to avoid elements after #n.
- If you can use array.new(...) to make an array from a list it seems to be confinient to have the unpack function in the metatable of array as well: 
MyArray:unpack() or array.unpack(MyArray) seems more natural than table.unpack(MyArray) even if it is the very same function. Which it would be assuming table.unpack is considering __len. 

Maybe this would mean to have both the 5.0 and the 5.1 solution, but the programmer would explicitly decide to use array by calling array.new.

The good thing is, in many cases it doesn't matter which kind of table it is, because of the use of the metamethods  __len and __ipairs, arrays would just often act the same as a sequence.

--
Thomas