I have a number of functions working on strings to extract interesting properties from these strings. One specific function, called many of these functions, is very expensive and ultimately generates a table of values:
local function expensive(s)
local t = nil
return function()
if not t then
t = {}
-- some expensive operations with s which add items to t
end
return t
end
end
local function fn1(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local function fn2(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local s1, s2 = 'a', 'b'
fn1(s1) -- should create the 't' table for s1
fn1(s2) -- should create the 't' table for s2
fn2(s1) -- should not create the 't' table again for s1
fn1(s2) -- should also not create the 't' table again for s2
How can I make an expensive function create a table exactly once in a row, returning a table anyway? I would prefer that the table is not presented to the global environment. I think this can probably be achieved with some clever use of closures, but I don't know the construction well enough.
source
share