lua-users home
lua-l archive

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

It's handy to expose built-in operators such as [] and .. as functions, so
you can do functional things with them.

Here's a nice trick: define

function subscript (t, s) return t[s] end

-- foldl: Fold a binary function through a list left associatively
--   f: function
--   e: element to place in left-most position
--   l: list
-- returns
--   r: result
foldl (f, e, l)
  local r = e
  for i = 1, getn (l) do
    r = f (r, l[i])
  return r

Then you can say

t = {a = {long = {path = {to = {the = {leaf = "hi!"}}}}}}
print (foldl (subscript, t, {"a", "long", "path", "to", "the", "leaf"}))



and you can define

function pathSubscript (t, s)
  return foldl (subscript, t, split ("%.", s)))

and say print (pathSubscript (t, "")), which gives


Handy for manipulating tables in programs (just use pathSubscript instead
of [] or dot; you could always put a wrapper around it so that it replaces
the usual gettable method if you like).

BTW, split has the obvious definition based on Perl's split. All this code
is available in my standard libraries (see

-- | perfect, a.  unsatirizable