在Lua 5.2中使2个以上模块递归引用的推荐方式 [英] Recommended way to have 2+ modules recursively refer to each other in Lua 5.2

查看:103
本文介绍了在Lua 5.2中使2个以上模块递归引用的推荐方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法

  • 两个Lua模块(我们叫它们AB)
  • 每个模块都使用彼此的功能,因此它们必须彼此require
  • 第三个模块(我们称其为C)可以使用A,但不能使用B,例如
  • Two Lua modules (let's call them A and B)
  • Each module uses functions from the other, so they must require each other
  • A third module (let's call it C) can use A but not B e.g.

C.lua:

local A = require 'A'

-- ...

A.foo()

  • 可能还有另一个模块D需要B,但不需要A和/或E同时需要AB
  • AB或它们的成员都不应添加到全局名称空间.
  • 避免使用modulesetfenv函数(在Lua 5.2中已弃用)
    • There may be another module D that requires B but not A and/or E requiring both A and B
    • Neither A nor B nor their members should be added to the global namespace.
    • Avoid using the module and setfenv functions (deprecated in Lua 5.2)
    • 相关: Lua-我该如何使用另一个库?(请注意:此解决方案无法处理循环依赖项.)

      Related: Lua - how do I use one lib from another? (note: this solution does not handle circular dependencies.)

      推荐答案

      我发现了一种非常简单的方法:

      I found quite a simple way to do it:

      A.lua:

      local A = {}
      local B
      
      function A.foo()
          B = B or require 'B'
          return B.bar()
      end
      
      function A.baz()
          return 42
      end
      
      return A
      

      B.lua:

      local B = {}
      local A
      
      function B.bar()
          A = A or require 'A'
          return A.baz()
      end
      
      return B
      

      这篇关于在Lua 5.2中使2个以上模块递归引用的推荐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆