V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
haoliang
V2EX  ›  程序员

试着用 luv 写个读取文件内容方法,实在是写不下去

  •  
  •   haoliang · 2022-09-11 19:35:38 +08:00 · 1245 次点击
    这是一个创建于 564 天前的主题,其中的信息可能已经有所发展或是发生改变。
    local uv = vim.loop
    
    local readall = function(path, callback)
      uv.fs_open(path, "r", 384, function(open_err, fd)
        assert(open_err == nil, open_err)
        uv.fs_stat(path, function(stat_err, stat)
          assert(stat_err == nil, stat_err)
          uv.fs_read(fd, stat.size, 0, function(read_err, data)
            assert(read_err == nil, read_err)
            assert(#data == stat.size)
            uv.fs_close(fd, function(close_err, success)
              assert(close_err == nil, close_err)
              assert(success)
              callback(data)
            end)
          end)
        end)
      end)
    end
    
    readall("/tmp/seq30", function(data)
      for _, line in ipairs(vim.split(data, "\n")) do
        print(line)
      end
    end)
    

    贴出来给大家瞅瞅啊。

    其实就一个 io.lines(path),写完上面这篇代码我不由得犹豫,我就写个小插件,有必要强上异步吗? 还只是个这么简单的需求。

    ( vim.loop 是 neovim 提供的 libuv/luv 访问入口)

    3 条回复    2022-09-12 20:05:06 +08:00
    pursuer
        1
    pursuer  
       2022-09-11 20:07:06 +08:00
    vim 不熟悉,不过 lua 有 promise 的实现,lua 中还可以用 yield 模拟 async/await 协程。
    haoliang
        2
    haoliang  
    OP
       2022-09-11 23:11:25 +08:00
    谢谢回复!巧了,我从聊天室里听到了相关的实现
    * https://github.com/kevinhwang91/promise-async
    * https://github.com/notomo/promise.nvim

    不过这两天的相关 lua 使用体验,我暂时不想用这种异步了; thread 、process 这样的一般实现我觉得够用,自己写的插件性能消耗可控
    zhuangzhuang1988
        3
    zhuangzhuang1988  
       2022-09-12 20:05:05 +08:00
    lua 的官方书上 有用 协程 举例 libuv 的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1127 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:54 · PVG 06:54 · LAX 15:54 · JFK 18:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.