I just starting to learn about OOP and make this script(module):
local Part = {} Part._index = Part function Part.Create(name, parent, size, position) local part = {newPart = Instance.new("Part")} setmetatable(part , Part) part.newPart.Name = name part.newPart.Parent = parent part.newPart.Size = size part.newPart.Position = position return part end function Part:ChangeColor(color) self.newPart.BrickColor = color end return Part
Another script:
local Part = require(game:GetService("ReplicatedStorage").CreatePart) script.Parent.MouseClick:Connect(function() local newPart = Part.Create("Stuff", game:GetService("Workspace"), Vector3.new(2, 2, 2), Vector3.new(0, 2, 0)) --Part.Create(name, parent, size, position) newPart:ChangeColor(BrickColor.new("Bright green")) --change the BrickColor of newPart end)
The first function is work, but the second one can't. When I try to use the function, it throw this error:
Workspace.Button.ClickDetector.Script:5: attempt to call method 'ChangeColor' (a nil value)
Thank for reading :D
You are setting table._index not table.__index.
Double underscores "__" are used to access the metamethods of a table.
local Part = {} Part._index = Part function Part.Create(name, parent, size, position) local part = {newPart = Instance.new("Part")} setmetatable(part , Part) part.newPart.Name = name part.newPart.Parent = parent part.newPart.Size = size part.newPart.Position = position return part end function Part:ChangeColor(color) self.newPart.BrickColor = color end return Part
On line 5 you have part instead of Part. Double check your code as lua is case sensitive:
local Part = require(game:GetService("ReplicatedStorage").CreatePart) script.Parent.MouseClick:Connect(function() local part = Part.Create("Stuff", game:GetService("Workspace"), Vector3.new(2, 2, 2), Vector3.new(0, 2, 0)) Part:ChangeColor(BrickColor.new("Bright green")) end)