Skip to content

Instantly share code, notes, and snippets.

@ildar
Created January 6, 2026 18:36
Show Gist options
  • Select an option

  • Save ildar/e5e9676f62a6b96ef2ac7b81be74ca12 to your computer and use it in GitHub Desktop.

Select an option

Save ildar/e5e9676f62a6b96ef2ac7b81be74ca12 to your computer and use it in GitHub Desktop.
local interface Animal
-- Associated function signature; `Self` refers to the implementor type.
new: function(string): self
-- Method signatures; these will return a string.
name: function(self): string
noise: function(self): string
talk: function(self)
end
local record Sheep is Animal
_naked: boolean
_name: string
end
-- impl Sheep
function Sheep:is_naked(): boolean
return self._naked
end
function Sheep:shear()
if self:is_naked() then
-- Implementor methods can use the implementor's trait methods.
print(self:name(), "is already naked...");
else
print(self._name, "gets a haircut!");
self._naked = true;
end
end
-- Implement the `Animal` trait for `Sheep`.
-- impl Animal for Sheep
-- `Self` is the implementor type: `Sheep`.
function Sheep.new(name: string): Sheep
local res: Sheep = { _name=name, _naked=false }
return setmetatable(res, {__index=Sheep})
end
function Sheep:name(): string
return self._name
end
function Sheep:noise(): string
if self:is_naked() then
return "baaaaah?"
else
return "baaaaah!"
end
end
function Sheep:talk()
-- For example, we can add some quiet contemplation.
print(self._name, "pauses briefly... ", self:noise());
end
-- fn main()
-- Type annotation is necessary in this case.
local dolly = Sheep.new("Dolly")
dolly:talk();
dolly:shear();
dolly:talk();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment