lua-users home
lua-l archive

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


The name of the '__close' metamethod suggests that the value supplied
as its first argument is about to pop out of usefulness if not out of
existence. In fact, all that is promised is that whenever a local
variable declared with <toclose> is initialized to that value, the
'__close' metamethod will be called when that local variable goes out
of scope.

This property can be exploited to implement journal-oriented programming.

We need two upvalues; let's call them 'journal' and 'ledger'. An inner
loop does some processing, putting stuff into 'journal' in an agreed
format. The '__close' metamethod of 'ledger' processes 'journal' by
e.g. extracting and storing data.

Now if we insert
  local <toclose> _ = ledger

into the inner loop, the journalling process is triggered.

Note that nothing stops 'ledger' from being the value assigned to more
than one local variable. For example, the following skeleton will call
ledger's '__close' metamethod after each word and at the end of each
line.

for line in io.lines() do
   local <toclose> _ = ledger
   for word in line:gmatch"%S+" do
     local <toclose> _ = ledger
     journal = word
   end
end

-- Dirk