lua - 在 Lua 中的单独函数调用之间缓存字符串上昂贵的表计算

标签 lua

我有许多对字符串进行操作的函数,以从这些字符串中提取有趣的属性。被许多函数调用的一个特定函数非常昂贵,并最终生成一个值表:

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

如何才能使昂贵的函数为每个字符串创建一次表,并在任一情况下返回表?我宁愿不让 table 暴露在全局环境中。我认为这可能可以通过巧妙地使用闭包来完成,但我不太了解其构造。

最佳答案

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

关于lua - 在 Lua 中的单独函数调用之间缓存字符串上昂贵的表计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44052959/

相关文章:

c++ - Lua C API - 使用同名的变量和函数加载多个文件

lua - 如何在 Lua 中将字符串的开头或结尾与 string.match 匹配?

python - brew install vim --with-lua 失败

c++ - Lua中具有大用户数据的有效垃圾收集

lua - 使用 Lua 使用 unicode 字符格式化字符串

function - 有没有办法在 Lua 中将本地函数按任意顺序排列?

c++ - 创建 Lua 状态时访问冲突

lua - 如何使用 pandoc lua 过滤器将标题添加为 1 级标题?

lua - Lua 中的析构函数?

lua - xmake总是报: error: cannot get program for cxx, 为什么?