Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Can't call method from module?

Asked by 4 years ago
Edited 4 years ago

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

Log in to vote
1
Answered by 4 years ago

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
It work. Thank you so much :D Block_manvn 395 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

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)
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. Block_manvn 395 — 4y

Answer this question