lua-users home
lua-l archive

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


On Fri, Dec 19, 2014 at 10:36 AM, Volodymyr Bezobiuk <dedoogun@gmail.com> wrote:
> Here's an idea and i hope we can have some kind of lazyness in Lua.


untested:


function new_lazy_t()
    local back_t = {}
    return setmetatable({}, {
        __newindex = function(t,k,v)
            if type(v)=='function' then
                back_t[k] = v
            else
                t[k] = v
            end
        end,
        __index = function(t, k)
            local v = back_t[k]
            if type(v) == 'function' then
                v = v()
            t[k] = v
            return v
        end,
    })
end


you create a 'lazy table', store functions there, and when you read
them they're evaluated and memoized:

local lt = new_lazy_t()
lt.magicnumber = function() very long calculations... end
print ('tadaaa', lt.magicnumber)

the only missing thing is short lambda syntax, but i don't find
'function()...end' so ugly.

-- 
Javier