Difference between a Method and a Function

I’m pretty new to scripting, and I’m currently a little confused about the difference between a method and a function

I’ve read that a method is a function, but I don’t understand why sources also tell me that a function is different from a method. What’s the difference?

All replies are greatly appreciated

1 Like

All methods are functions.
But not all functions are methods.

A function is a standalone block of code.
A method is a function that belongs to a table or object.

Function

function speak()
	print("Hello")
end
speak()

Method

local obj = {}
function obj:speak()
	print("Hello")
end
obj:speak()

It’s a bigger deal in strict OOP languages like Java, C#, Python, and Ruby.
In Lua, thinking of them all as functions works fine, but there is a difference.

What I mean by that is this has to be defined as that in them languages.
In Lua they can be used on the fly. There’s no enforced class system.

3 Likes

A Method is just a function that is inside a table called using the : operator.

local t = {}

t.printname = function(tab:{},c:number)
--this function will list out all members of a table, no more than c times
for i = 1,c do
if tab[i] then
print(tab[i] else break end
end
end


end


To call the function in the table you’d need to have another table at hand, but if you wanted to run the function passing the t the table itself, you could call the function as a method, which passes the table itself as the first argument

local t = {1,2,3}
t.printname(t, 3)
--functionally equivalent to...
t:printname(3)

lots of methods are made specifically for for manipulating the table they belong to. The first argument when initializing those functions would be self, which is a keyword for that purpose.

In short, methods are specific functions belonging to a table that usually serve the purpose of altering that specific table its being called from.

3 Likes