Search code examples
moduleluareferencerequire

lua 'require' duplicating table


What I am trying to do is; use a module to create two distinct and separate tables but what seems to be happening is; if I have already used 'require' then it will give me a reference to the previous require what I really want is just the value/a copy of the module. I cannot use 'dofile' because 1). I need to use relative paths and 2). I am building this in Corona for android and as I understand 'dofile' does not work well with .apk.

Here is my code.

This is my main.lua

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

bar:changeName()

assert(foo.name ~= bar.name)

this is in %cd%/modules/myModule

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

Solution

  • Your module can return constructor of M instead of M


    Your module:

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

    Your main script:

    foo = require('modules.myModule')()
    bar = require('modules.myModule')()
    
    bar:changeName()
    
    assert(foo.name ~= bar.name)