Scope for more than one instance of one Required Module?

In Scene A, we require Module X twice by 2 local variables modA and modB:

 local modA = require("moduleX") local modB = require("moduleX") modA.new() modB.new() modA.printIt () modB.printIt ()

Module X looks like:

local M = {} function M.new () local count = 0 function M.printIt () count = count + 1 print("count = ", count) end end return M

I would have expected this to output “count = 1” twice as there are 2 versions of count each one local to modA and modB. But it prints “count = 1” and “count = 2”. So not sure what’s going on. Firstly why is this the case and secondly how to achieve the original expectation?

Many thanks.

Lua doesn’t have classes and instances like other OO languages.  

The require function is for loading “libraries”, not classes.   It automatically prevents loading the same library twice – The second call to require is going to see that you’ve already required the library, and just return a reference to it.   ModA and ModB are just two “pointers” to the loaded library.

Hope this makes sense.  

This is one way, using meta tables: https://www.youtube.com/watch?v=CYxMfVy5W00

Scene A:

[lua]local ModuleX = require(“moduleX”)

local modA = ModuleX.new()

local modB = ModuleX.new()

modA:printIt ()

modB:printIt ()[/lua]

moduleX:

[lua]local M = {}

local M_mt = { __index = M }

function M.new ()

local moduleProperties = {

count = 0

}

return setmetatable( moduleProperties, M_mt )

end

function M:printIt ()

self.count = self.count + 1

print("count = ", self.count)

end

return M[/lua]

Sorry, forum butchered indenting.

Ah ok, metatables. Thanks JonJonsson. Very clear explanation and video. Will give it a go.

Lua doesn’t have classes and instances like other OO languages.  

The require function is for loading “libraries”, not classes.   It automatically prevents loading the same library twice – The second call to require is going to see that you’ve already required the library, and just return a reference to it.   ModA and ModB are just two “pointers” to the loaded library.

Hope this makes sense.  

This is one way, using meta tables: https://www.youtube.com/watch?v=CYxMfVy5W00

Scene A:

[lua]local ModuleX = require(“moduleX”)

local modA = ModuleX.new()

local modB = ModuleX.new()

modA:printIt ()

modB:printIt ()[/lua]

moduleX:

[lua]local M = {}

local M_mt = { __index = M }

function M.new ()

local moduleProperties = {

count = 0

}

return setmetatable( moduleProperties, M_mt )

end

function M:printIt ()

self.count = self.count + 1

print("count = ", self.count)

end

return M[/lua]

Sorry, forum butchered indenting.

Ah ok, metatables. Thanks JonJonsson. Very clear explanation and video. Will give it a go.