lua-users home
lua-l archive

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


On Thu, 7 Mar 2013 11:26:49 +0200
steve donovan <steve.j.donovan@gmail.com> wrote:

> On Thu, Mar 7, 2013 at 11:06 AM, Steve Litt
> <slitt@troubleshooters.com> wrote:
> > I really like the table-centricity.
> 
> Oh yes, one data structure does all! It's so convenient to have an
> 'array' which also has a 'map' part of key/value pairs.
> 
> Newcomers do however bump into table uses which will confuse them.
> Yes, you can use a Lua table as a 'sparse array' but then don't trust
> the built-in #!  In Lua 5.2, give it a metatable and a __len
> metamethmod and define # to be exactly what you mean. (May be more
> efficient to use an index array in this case; the user need not know
> this.)
> 
> Plus, remember the limitations of the table.* functions; they mostly
> assume _arrays_, which are defined as sequences of elements
> {[1]='a',[2]='b',...} with no holes, like table.sort and table.concat.
>  table.insert should be used with caution since it can introduce holes
> if the index isn't 1 to #t+1.
> 
> steve d.

Yeah, that stuff can byte you. The way I avoid that is, if I intend a
table to be an array, a stack or a queue, I use only numeric
subscripts starting with 1 and make sure everything's numeric and
contiguous. If I need any extra info about the array, I include the
array as an element in a key/value style table, and make one of the
other keys the info for the array. Sure, it would be convenient to
have a few non-numeric keys in the array itself, but for safety I just
put them elsewhere. 

SteveT

Steve Litt                *  http://www.troubleshooters.com/
Troubleshooting Training  *  Human Performance