So I want to make an object that can be created in multiple scripts, so I went with this approach:
Module Script Example:
local module = {} Object = {} function module:constructObject(x, y) return setmetatable({x = x, y = y}, Object) end Object.__index = Object function Object:getX() return self.x end function Object:getY() return self.y end return module
Now if I were to construct the object in another script written in the module above and call one of its methods, it would be considered to be nil. Is there a way around having to write object methods that are considered to be nil when called from a script that requires from the module?
Your wording is a bit confusing, but hopefully this will help. The way that I create object oriented style classes in Lua is with the closure-based objects described at the bottom of this page: http://lua-users.org/wiki/ObjectOrientationTutorial
Doing it this way, you can write your module script like so:
local MyModule = {} function MyModule.new(x, y) local self = {} -- Local variables are private to your class local x = x local y = y -- Public variables can be created like this self.thisIsPublic = "Hello World" -- A private function local function CombineString(str) return str .. "!!" end -- A public function function self.PrintStuff() print(CombineString(self.thisIsPublic), x, y) end return self end return MyModule
Then in another script somewhere:
local MyModule = require(game.ServerStorage.MyModule) local m1 = MyModule.new(4, 5) print(m1.thisIsPublic) m1.PrintStuff() -- Notice the . syntax, not : local m2 = MyModule.new(1, 3) m2.PrintStuff() m1.PrintStuff()
Which outputs:
Hello World
Hello World!! 4 5
Hello World!! 1 3
Hello World!! 4 5
So you can see that every object you create this way is a seperate instance. I hope this helped.