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 5 years ago
Edited 5 years ago

I just starting to learn about OOP and make this script(module):

01local Part = {}
02Part._index = Part
03 
04function Part.Create(name, parent, size, position)
05    local part = {newPart = Instance.new("Part")}
06    setmetatable(part , Part)
07 
08    part.newPart.Name = name
09    part.newPart.Parent = parent
10    part.newPart.Size = size
11    part.newPart.Position = position
12 
13    return part
14end
15 
16function Part:ChangeColor(color)
17    self.newPart.BrickColor = color
18end
19 
20return Part

Another script:

1local Part = require(game:GetService("ReplicatedStorage").CreatePart)
2 
3script.Parent.MouseClick:Connect(function()
4    local newPart = Part.Create("Stuff", game:GetService("Workspace"), Vector3.new(2, 2, 2), Vector3.new(0, 2, 0))
5 --Part.Create(name, parent, size, position)
6    newPart:ChangeColor(BrickColor.new("Bright green")) --change the BrickColor of newPart
7end)

The first function is work, but the second one can't. When I try to use the function, it throw this error:

1Workspace.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 5 years ago

You are setting table._index not table.__index.

Double underscores "__" are used to access the metamethods of a table.

01local Part = {}
02Part._index = Part
03 
04function Part.Create(name, parent, size, position)
05    local part = {newPart = Instance.new("Part")}
06    setmetatable(part , Part)
07 
08    part.newPart.Name = name
09    part.newPart.Parent = parent
10    part.newPart.Size = size
11    part.newPart.Position = position
12 
13    return part
14end
15 
16function Part:ChangeColor(color)
17    self.newPart.BrickColor = color
18end
19 
20return Part
1
It work. Thank you so much :D Block_manvn 395 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

On line 5 you have part instead of Part. Double check your code as lua is case sensitive:

1local Part = require(game:GetService("ReplicatedStorage").CreatePart)
2 
3script.Parent.MouseClick:Connect(function()
4    local part = Part.Create("Stuff", game:GetService("Workspace"), Vector3.new(2, 2, 2), Vector3.new(0, 2, 0))
5    Part:ChangeColor(BrickColor.new("Bright green"))
6end)
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 — 5y

Answer this question