加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 21:45:54 所属栏目:大数据 来源:网络整理
导读:我有许多函数在字符串上运行,以从这些字符串中提取有趣的属性.许多这些函数调用的一个特定函数非常昂贵,并最终生成一个值表: local function expensive(s) local t = nil return function() if not t then t = {} -- some expensive operations with s whic
我有许多函数在字符串上运行,以从这些字符串中提取有趣的属性.许多这些函数调用的一个特定函数非常昂贵,并最终生成一个值表:

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

我怎样才能使昂贵的函数每个字符串只创建一次表,在任何一种情况下返回表?我宁愿没有将表暴露给全局环境.我认为这可能是通过巧妙地使用闭包来实现的,但我不太了解这个结构.

解决方法

Egor的答案将完成这项工作,但整个文件都可以访问缓存表.要隐藏它,您有几个选择.第一个是简单的do / end块.

local expensive
do
    local cache = {}
    expensive = function (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
end

另一种是自动执行功能.

local expensive = (function ()
    local cache = {}
    return function (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
end)()

自执行功能的优点是您只需要定义一次昂贵的函数名称,但缺点是它比do / end块更难读取.否则他们几乎是一样的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读