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

What’s the Significance of Self residing in the Equation?

I’m fooling around with metatables and I though to myself, what’s the point of adding Self to Class? As in the example below, you can perfectly run this metamethod, if that’s the correct Terminology, without putting Self into the mix, I’d also like to understand a bit more on Self being an automatically provided argument when writing these functions. Could anyone fill me in?

--// Self applied
local Class = {};

Class.__index = Class

local Self = {};
setmetatable(Self, Class)

function Class.SetString(Self, String)  --// Provided argument?
   Class.String = String
   return Class.String
end

print(Self:SetString("Hello!")) --// -> “Hello!”

--// Self excluded

local Class = {};

Class.__index = Class

function Class.SetString(Self, String)
   Class.String = String
   return Class.String
end

print(Class:SetString("Hello!")) --// -> “Hello!”

Thanks! If there’s anything else interesting that I should know, please provide a link!

1 answer

✓ Accepted answer

You don't have to include self as a parameter, it's already declared when you use a method on your object.

Heres some reading that already explains it much better than I can.

local dog = {}
dog.__index = dog

function dog.new(name, breed)
	local newdog = setmetatable({}, dog)
	newdog.name = name or 'defaultdog'
	newdog.breed = breed or 'defaultbreed'
	newdog.age = 1
	newdog.doggyage = newdog.age * 2
	return newdog
end

function dog:dogage(newage)
	self.age = newage
	self.doggyage = newage * 7
	return 	self.age, self.doggyage
end

local mydog = dog.new('pete', 'golden')
local newage, doggyage = dog:dogage(2)
print ( string.format('My dog %s is %d years old in doggy years!', mydog.name, doggyage) )

1 comment

1

I’m so sorry I left this blank. My knowledge of programming has widely increased, and I understand this subject now fully. I came back to this and realized I never accepted. Please do accept my deepest of apologies.

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