Cannot get Class's property in seperated Event inside Class

What I did:
Create Proximity Promt, parent it to a part
Create Event function of ProximityPrompt triggering

Module code:

local Hide = {}
Hide.__index = Hide
function Hide.new()
	local newHide = {}
	setmetatable(newHide, Hide)
	newHide.proximity = Instance.new("ProximityPrompt")
	newHide.proximity.Parent = script.Parent:FindFirstChild("hidingPlate")
	newHide.proximity.Triggered:Connect(function()
		Hide:ProximityEvent()
	end)
	return newHide
end

function Hide:ProximityEvent()
	print(self.proximity)
end

return Hide

Normal Script:

The Hide:ProximityEvent couldn’t print self.proximity and gave me an error: attempt to index nil with ‘proximity’
thanks.

1 Like

There is an important difference between the . and the : function calling convention. . simply calls the function on the table, but : will automatically provide self to the function as the table it was called on:

local myTable = {
    SomeValue = 42
}

function myTable:getSelf()
    return self
end

-- FALSE
print(myTable.getSelf() == myTable)
-- TRUE
print(myTable:getSelf() == myTable)

myTable.getSelf will return nil, but myTable:getSelf will return myTable, as the : operator sets myTable as self in the function.

Also, Questions go in #help-and-feedback. Because this is a programming/scripting question, it goes in #help-and-feedback:scripting-support. In #development-discussion, you cannot mark Solutions.

1 Like

I fixed the problem and I changed it to : then
I thought my code works completely fine and slept but it is still unable to get the property.
image
It outputted ProximityPromt when I started the program then when I press the proximitypromt it prints nil

1 Like

You need to call ProximityEvent on newHide, not Hide, in the .Triggered event.

1 Like

Yeah, I see now. The property was created and stored in the copied class, newHide. That’s why. Thanks alot.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.