lua 'require' 复制 table

lua 'require' duplicating table

我想做的是;使用一个模块创建两个不同且独立的表,但似乎正在发生的是;如果我已经使用了 'require' 那么它会给我一个对之前 require 的引用 我 really 想要的只是模块的 value/a 副本。我不能使用 'dofile' 因为 1)。我需要使用相对路径和 2)。我正在为 android 在 Corona 中构建这个,据我了解 'dofile' 不能很好地与 .apk 一起使用。

这是我的代码。

这是我的main.lua

foo = require('modules.myModule')
bar = require('modules.myModule')

bar:changeName()

assert(foo.name ~= bar.name)

这是在 %cd%/modules/myModule

local M = {
    name = "hai",
    changeName = function(self)
        self.name = 'not_hai'
    end
}
return M

您的模块可以 return M 的构造函数而不是 M


您的模块:

return 
   function()  -- this is a constructor of M
      local M = {
         name = "hai",
         changeName = function(self)
            self.name = 'not_hai'
         end
      }
      return M
   end

您的主要脚本:

foo = require('modules.myModule')()
bar = require('modules.myModule')()

bar:changeName()

assert(foo.name ~= bar.name)

作为变体,您可以使用这个不需要的函数:

function unrequire(m)
    package.loaded[m] = nil
    _G[m] = nil
end

foo = require('myModule')
unrequire('myModule')
bar = require('myModule')

这是我编写模块的方式

local M = {}

function M.new()
  local myTable = { name = "hai" }

  myTable:changeName ()
    self.name = 'not_hai'
  end

  return myTable
end

return M

用法:

local m = require('myModule')

foo = m.new()
bar = m.new()

bar:changeName()