Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching expensive table calculation on strings between separate function calls in Lua

Tags:

lua

I have a number of functions operating on strings to extract interesting properties from those strings. One particular function which is called by many of those 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 it so that the expensive function creates the table exactly once per string, returning the table in either case? I would rather not have the table exposed to the global environment. I think this could probably be accomplished by some clever use of closures, but I don't know the construct well enough.

like image 727
ruser9575ba6f Avatar asked May 18 '17 16:05

ruser9575ba6f


1 Answers

local cache = {}

local function expensive(s)
  local t = cache[s]
  if not t then
    t = {}
    -- some expensive operations with s which add items to t
    cache[s] = t
  end
  return t
end
like image 185
Egor Skriptunoff Avatar answered Oct 21 '22 13:10

Egor Skriptunoff