[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Exposing [] as a function
- From: Reuben Thomas <rrt@...>
- Date: Wed, 24 Jul 2002 15:02:14 +0100 (BST)
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
function
foldl (f, e, l)
local r = e
for i = 1, getn (l) do
r = f (r, l[i])
end
return r
end
Then you can say
t = {a = {long = {path = {to = {the = {leaf = "hi!"}}}}}}
print (foldl (subscript, t, {"a", "long", "path", "to", "the", "leaf"}))
gives
hi!
and you can define
function pathSubscript (t, s)
return foldl (subscript, t, split ("%.", s)))
end
and say print (pathSubscript (t, "a.long.path.to.the.leaf")), which gives
hi!
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
http://lua-users.org/wiki/StandardLibraries).
--
http://www.mupsych.org/~rrt/ | perfect, a. unsatirizable