prapin suggestion to use metatables to represent a sequence representation, much like I would do. An abstraction that can help is defining meta-tagging for segments, which can be a 0-ary function that returns a table pair and an offset index - we only use functions here to represent tuples. Then we can define a metatable that makes this function behave like a table:
do local tail_mt = { __index = function(f, k) local t, i=f(); return t[k+i] end, __newindex = function(f, k, v) local t,i=f(); t[k+1] = v end, __len = function(f) local t,i=f(); return #ti end, __ipairs = function(f) local t,i = f () return function (_, j) if i+j>=#t then return nil else return j+1, t[i+j+1] end end, nil, 0 end, } tail_mt.__pairs = tail_mt.__ipairs -- prapin collapsed this functionality, so I do too function tail (t) if type(t) == "table" then return setmetatable ( function () return t, 1 end, tail_mt ) elseif type(t) == "function" then local t1, i = t () return setmetatable ( function () return t1, i+1 end, tail_mt ) end end end
With the __index and __newindex metamethods, you can write code, for example f [2] = f [1] +1.
Although this (untested) code does not endlessly create one-time meta tags, it is probably less efficient than prapin's, as it will call thunks (0-ary functions) to get its contents. But if you might be interested in expanding the functionality by, say, having more general views on the sequence, I think that is a little more flexible.
source share