teal-language / tl

The compiler for Teal, a typed dialect of Lua
MIT License
2.04k stars 101 forks source link

In-record function definitions #624

Open Frityet opened 1 year ago

Frityet commented 1 year ago

It would be really cool to be able to define functions inside a record, like so

local record Person
        name: string
        age: integer

        function create(name: string, age: integer)
                local self = setmetatable({}, Person)
                self.name = name
                self.age = age
                return self
        end

        function say(self, message: string)
                print(self.name.." says "..message)
        end
end

local frit = Person.create("Frityet", 16)
frit:say "Hello, World!"

The equivalent would be in regular teal:

local record Person
        name: string
        age: integer

        create: function(string, integer)
        say: function(Person, string)
end

function Person.create(name: string, age: integer)
        local self = setmetatable({}, Person)
        self.name = name
        self.age = age
        return self
end

function Person:say(message: string)
        print(self.name.." says "..message)
end

This allows for more compact definitions of records, whilst also creating cleaner code.

lewis6991 commented 1 year ago

Doesn't this stray away a little too much from Lua?

catwell commented 1 year ago

It does not make sense for me because a record is an interface and not an implementation.

I can see how such a mechanism could generate code based on metatables and so on but I do not think Teal should do this.

hishamhm commented 1 year ago

It's not something I intend to implement for records in the foreseeable future.