I have two classes, Ore and Chunk. Ore is basically a wrapper for Model. Chunk is another wrapper for Model, but serves the purpose of containing multiple Ores, and getting data for the current position in the quarry, like perlin noise or poisson disc distributions for Ores.
These 2 classes need to require() eachother, but obviously thats not possible unless I define both in one module. (yields Requested module was required recursively)
I saw somewhere that if your classes need to depend on eachother, they’ve not been created correctly. Would this be the case here?
That last part is not true, a class in general can depend in a cycle with other classes or even depend on itself, assuming you mean design-wise.
Presumably your modules depend on eachother because some code in your functions needs to know the functions of the opposite class. However, since you aren’t actually executing this at the time you require(). You get around this:
In Chunk, declare Ore but do not define it local Chunk
In Ore, instead of making and return a module the normal way, create a new function which encloses everything and returns the module, and takes the Chunk module as an argument
Back in Chunk, create you module the normal way, but right before you return the Chunk module, require(Ore) and call the function with Chunk as its argument:
Chunk module:
local Chunk = {}
local Ore
function Chunk.Thingy()
Ore.Something()
end
--Returns a function, doesn't create anything in the module yet
local OreWrapper = require(Ore)
Ore = OreWrapper.Create(Chunk)
return Chunk
Ore module:
local wrapper = {}
function wrapper.Create(Chunk)
local Ore = {}
function OreThingy()
Chunk.Anything()
end
return Ore
end
return wrapper
Note that declaring Ore beforehand in Chunk is not syntactically necessary, but it makes it clear that you are deferring assignment until later.