Skip to content

Breaking classes with method names #256

@tomblind

Description

@tomblind
class Foo {
    public method() { return "foo"; }
    public static method() { return "bar"; }
}
const bar = new Foo();
print(bar.method());
print(Foo.method());
Foo = Foo or {}
Foo.__index = Foo
function Foo.new(construct, ...)
    local self = setmetatable({}, Foo)
    if construct and Foo.constructor then Foo.constructor(self, ...) end
    return self
end
function Foo.constructor(self)
end
function Foo.method(self)
    return "foo"
end
function Foo.method(self) --Overrides previous definition!!
    return "bar"
end
local bar = Foo.new(true);
print(bar:method()); --prints "bar"!
print(Foo:method());

A common solution to this in lua bindings to other languages is to split classes into 2 tables: a class table with static methods and properties, and a separate metatable that provides all of the instance methods. Doing this would also get things closer to what's needed for #206.

Bonus problem:

class Foo {
    public new() {}
}
const foo = new Foo();
Foo = Foo or {}
Foo.__index = Foo
function Foo.new(construct, ...)
    local self = setmetatable({}, Foo)
    if construct and Foo.constructor then Foo.constructor(self, ...) end
    return self
end
function Foo.constructor(self)
end
function Foo.new(self) --Uh-oh...
end
local foo = Foo.new(true);

Perhaps adding new to the list of dis-allowed identifier names would be a good idea (also, maybe 'self' too).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions