lua-users home
lua-l archive

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



>> In a parallel universe far from here, I am
>> currently finalizing srfi-40 for streams; would an
>> explicit delay/force, as in scheme, fit the language?

> How does this differ from nullary closures?

I think the difference is that delay/force tries to guarantee that
the computation only happens once. This can be done with a nullary
closure, but it requires some machinery.

ej.

local lazyExpensiveComputation()
do
  local val, forced
  function lazyExpensiveComputation()
    if forced then return val end
    forced = true
    val = expensiveComputation()
  end
end

Of course, that can get wrapped up in a factory:

function delay(fn, ...)
  local val, forced
  return function()
    if forced then return val end
    forced = true
    val = fn(unpack(arg))
    arg = nil
    return val
  end
end

force is just a function call.

Another interesting approach would be to use a coroutine, something like this:

delayedComputation = coroutine.wrap(
  function(x)
    x = expensiveComputation(x)
    while true do coroutine.yield(x) end
  end)