lua-users home
lua-l archive

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

On Tue, Jan 4, 2011 at 16:47, Gavin Wraith <> wrote:
> [..snip..]
> I note that other programming languages make a distinction between
> "lists" (indices a consecutive sequence of integers starting at 1 or
> 0 or whatever) and "hash tables", usually with strings as indices.
> That Lua amalgamates and extends the two seems to me to be one of
> its most interesting aspects. So how do others exploit this
> amalgamation in their Lua programming?
> For myself, I often have lists and then find it useful to add methods
> to them - something that would not be so convenient if lists and hash
> tables were separate notions. I tend to use the list simply as a stack,
> with non-nil entries, so the hole problem never arises. But maybe I am
> overlooking other useful ways of exploiting the amalgamation?
> In any case it seems to me that it would be good PR for Lua if
> in example code snippets those idioms which are currently unique to Lua
> were to be highlighted.

Despite my apparent rants about tables with holes I like this
amalgamation of hashes and arrays a lot and extensively use it.

Here is a snippet that allows arbitrary mix of positional and named
arguments in  function calls and allows for default values as an icing
on a cake.

function foo(fat) -- fat stays for Function Argument Table
  local x= fat.x or fat[1] or 11
  local y= fat.y or fat[2] or 22
  local z= fat.z or fat[3] or 33
  return x+y+z

can be called as foo{1,2,3} or foo{1,y=2} or foo{x=1,y=2, z=3} or foo{}.
Even foo{1,x=55} where named argument will take precedence over
corresponding positional. This policy can be reversed by swapping
arguments of 'or' in the function body.

Indeed, unified  table=hash+array  is a very nice feature that sets
Lua apart in a good way.