I just starting to learn about OOP and make this script(module):
01 | local Part = { } |
02 | Part._index = Part |
03 |
04 | function 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 |
14 | end |
15 |
16 | function Part:ChangeColor(color) |
17 | self.newPart.BrickColor = color |
18 | end |
19 |
20 | return Part |
Another script:
1 | local Part = require(game:GetService( "ReplicatedStorage" ).CreatePart) |
2 |
3 | script.Parent.MouseClick:Connect( function () |
4 | local newPart = Part.Create( "Stuff" , game:GetService( "Workspace" ), Vector 3. new( 2 , 2 , 2 ), Vector 3. new( 0 , 2 , 0 )) |
5 | --Part.Create(name, parent, size, position) |
6 | newPart:ChangeColor(BrickColor.new( "Bright green" )) --change the BrickColor of newPart |
7 | end ) |
The first function is work, but the second one can't. When I try to use the function, it throw this error:
1 | 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.
01 | local Part = { } |
02 | Part._index = Part |
03 |
04 | function 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 |
14 | end |
15 |
16 | function Part:ChangeColor(color) |
17 | self.newPart.BrickColor = color |
18 | end |
19 |
20 | return Part |
On line 5 you have part instead of Part. Double check your code as lua is case sensitive:
1 | local Part = require(game:GetService( "ReplicatedStorage" ).CreatePart) |
2 |
3 | script.Parent.MouseClick:Connect( function () |
4 | local part = Part.Create( "Stuff" , game:GetService( "Workspace" ), Vector 3. new( 2 , 2 , 2 ), Vector 3. new( 0 , 2 , 0 )) |
5 | Part:ChangeColor(BrickColor.new( "Bright green" )) |
6 | end ) |