Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can't call method from module?

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

2 answers

✓ Accepted answer

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

1 comment

1

It work. Thank you so much :D

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)

1 comment

0

That won't work, because "Part" is a Module that contain the function to change the color of a part and "part" is a new part that I just made.

This discussion is preserved as it was. New answers, comments, and votes are closed.