classic icon indicating copy to clipboard operation
classic copied to clipboard

using :new() for creating instances silently fails

Open riidom opened this issue 5 years ago • 2 comments

For clarification: If you have a class Point (like the example in the docs), and then want to create a new Point which is correctly done so: local p = Point(3,4) But if you instead do: local p = Point:new(3,4) it just does nothing. Maybe it's just me who ran into this, but the mistake was not very obvious. Raising an error as hint would be nice, or allowing it as kind of alternative syntax. Whichever is easier, I guess.

riidom avatar Nov 30 '20 06:11 riidom

Yeah, I just had to debug this for an hour when trying to setup the Bytepath Love2d tutorial. An error message, or at least a warning in the README would be useful.

arnavb avatar Jan 17 '21 18:01 arnavb

I know this old, but in case anyone else has a similar experience: I think this comes down to the fact that :new is really an initializer and :init would probably be a more fitting name. When you do Point:new(3,4) you're setting the static variables on the Point class itself to the given values.

As for hinting, it doesn't seem possible to throw a warning when calling :new since there isn't a way to distinguish whether it's being invoked directly or inside of classic's __call method. Allowing it as an alternative syntax would be up to rxi, but you can easily modify your copy of the project to behave the way you want. Still, the current behavior is useful for re-initializing object instances (in object pooling, for example). It's easy as:

local p = Point(3,4)
--- do stuff
p:new(4, 5) -- re-init to new values

Aweptimum avatar Nov 01 '21 16:11 Aweptimum