lua-users home
lua-l archive

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


Simple closure:

function enclose(fn, ...) return function() fn(unpack(arg)) end end

"Promise" (only calls the function once):

function promise(fn, ...)
  local doit
  function doit()
    local rv = fn(unpack(arg))
    function doit() return rv end
    return rv
  end
  return function() return doit() end
end

-- if you like to be explicit
function force(owed) return owed() end


Sample:

> massive = {}; for i = 1, 1000000 do massive[i] = i end
> collectgarbage()
> =gcinfo()
16414   32828
> size = promise(table.getn, massive)
> massive = nil
> =gcinfo()
16416   32828
> collectgarbage()
> =gcinfo()
16414   32828
> =force(size)
1000000
> =gcinfo()
16415   32828
> collectgarbage()
> =gcinfo()
30      60

> greet = promise(function() io.write("Who do you want to greet? ")
>>                           return "Hello, " .. io.read()
>>                           end
>> )
> =greet()
Who do you want to greet? World
Hello, World
> =greet()
Hello, World
>