Skip to content

Extract new operator and class creation boilerplate to a lualib #709

@ark120202

Description

@ark120202

Was discussed in Discord a while back.

Input:

class A {}
new A(args);

Current result:

A = ...
function A.new(...)
    local self = setmetatable({}, A.prototype)
    self:____constructor(...)
    return self
end
A.new(args)

Proposed Result:

function __TS_New(class, ...)
    local self = setmetatable({}, class.prototype)
    return self:____constructor(...) or self
end

A = ...
__TS_New(A, args)

Input:

class A {}
class B extends A {}

Current Result:

A = {}
A.name = "A"
A.__index = A
A.prototype = {}
A.prototype.__index = A.prototype
A.prototype.constructor = A
B = {}
B.name = "B"
B.__index = B
B.prototype = {}
B.prototype.__index = B.prototype
B.prototype.constructor = B
B.____super = A
setmetatable(B, B.____super)
setmetatable(B.prototype, B.____super.prototype)

Proposed Result:

function __TS_CreateClass()
    local class = {}
    class.__index = class
    class.name = name
    class.prototype = {}
    class.prototype.__index = class.prototype
    class.prototype.constructor = class
    return class
end

function __TS_ClassExtends(class, base)
	class.____super = base
    setmetatable(class, class.____super)
    setmetatable(class.prototype, class.____super.prototype)
end

A = __TS_CreateClass()
A.name = "A"
B = __TS_CreateClass()
B.name = "B"
__TS_ClassExtends(B, A)

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