Mayron
Mayron

Reputation: 2394

Lua - Should I use ":" when defining functions in tables if not using the "self" keyword?

This is more of a design philosophy question as I already know you shouldn't call a function with : (object-oriented syntactic sugar) if the function has been defined without the self keyword by using .. But the problem is that programmers using a library I have created tend to not read the documentation and run into the question of "how should I call your function?", so I end up always defining functions using the method below:

local tbl = {};
function tbl:Add(a, b)
   return a + b;
end

I have installed Luacheck (in VS Code) and it often complains when I use this syntax and not use the self referential keyword. It says: [luacheck] unused argument "self". Is there any problem with this in terms of performance (or is there a way of disabling Luacheck in VS Code)?

I prefer writing functions in this style as opposed to the style below:

function tbl.Add(_, a, b)
    return a + b;
end

It seems a pain to have to add a dummy variable at the start of the parameter list.

EDIT: Another problem is what if you had many tables that implement a function with the same name and want to iterate over them but some implementations do not use the self argument and others do? It would be very tedious and bad design to check what type of table it is to call the function correctly.

What is the preferred style? A bit confused in general about this warning. What are your thoughts? Thanks.

Upvotes: 3

Views: 958

Answers (1)

Ivo
Ivo

Reputation: 23164

if you're not using the self argument you can just do

function tbl.Add(a, b)
    return a + b;
end

no need to use a dummy variable.

You just need to be sure then that you also call it with a . and not a :
so

local someValue = tbl.Add(1, 3)

for example and not

local someValue = tbl:Add(1, 3)

Upvotes: 1

Related Questions