-
In the tutorial, there's this paragraph and example:
function Point:move(dx: number, dy: number)
self.x = self.x + dx
self.y = self.y + dy
end This works, however, I'm curious if it's possible to do the same thing on a nested record like this? local record Math
record Point
x: number
y: number
end
end
function Math.Point:move(dx: number, dy: number)
self.x = self.x + dx
self.y = self.y + dy
end The code above gives the error "cannot add undeclared function 'move' outside of the scope where 'Math.Point' was originally declared", but I don't didn't understood how to declare it on the correct scope. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Just after making the post I noticed how to do it, sorry 😅. This solves the problem: local record Math
record Point
x: number
y: number
end
end
local Point = Math.Point
function Point.new(x: number, y: number): Point
local p: Point = {x=x, y=y}
return setmetatable(p, {__index=Point})
end
function Point:move(dx: number, dy: number)
self.x = self.x + dx
self.y = self.y + dy
end
local p = Point.new(3,3)
p:move(2,3)
print(p.x,p.y) -- output: 5 6 I'll keep the thread open in case there's a more appropriate way. |
Beta Was this translation helpful? Give feedback.
-
Making a correction here, the above method (by aliasing) doesn't works with nested records (with more depth than 1) and don't seems to be the apropriate way of declaring functions either. The following way, described by the tutorial, it's reliable and works in any nesting level:
Closing. |
Beta Was this translation helpful? Give feedback.
-
This was a bug which is now fixed! Your original example now typechecks in |
Beta Was this translation helpful? Give feedback.
Making a correction here, the above method (by aliasing) doesn't works with nested records (with more depth than 1) and don't seems to be the apropriate way of declaring functions either.
The following way, described by the tutorial, it's reliable and works in any nesting level:
Closing.