So, Luau, Roblox’s superset of Lua, is fantastic! As someone who comes from a primarily statically-typed background in software engineering, this makes me far more eager to engage with Lua.
I do have a problem, though. Assume I have a class designed to, I don’t know, represent a location on a Chessboard:
Try 1
--!strict
--- A class representing a square's position on a Chess board.
-- @classmod ChessPosition
local ChessPosition = {};
ChessPosition.prototype = {};
ChessPosition.prototype.__index = ChessPosition.prototype;
--- A map-like object that maps a chess square's column (file) numerical value to
--- its corresponding character.
ChessPosition.columnToCharacterMap = {
[1] = "a",
[2] = "b",
[3] = "c",
[4] = "d",
[5] = "e",
[6] = "f",
[7] = "g",
[8] = "h",
};
--- A type alias describing the shape of a ChessPosition instance.
type ChessPosition = {
column: number;
row: number;
toNotation: (ChessPosition) -> string;
};
--- Construct a new ChessPosition from a numeric column and row.
-- @param column The value in the range [1, 8] assigned to the ChessPosition's column.
-- @param row The value in the range [1, 8] assigned to the ChessPosition's row.
function ChessPosition.new(column: number, row: number): ChessPosition
local self = {};
setmetatable(self, ChessPosition.prototype);
self.column = column;
self.row = row;
return self;
end
--- Convert the ChessPosition object to standard algebraic notation (SAN).
function ChessPosition.prototype.toNotation(self: ChessPosition): string
local columnAsCharacter = ChessPosition.columnToCharacterMap[self.column];
local asNotation = ("%s%d"):format(columnAsCharacter, self.row);
return asNotation;
end
local a1 = ChessPosition.new(1, 1):toNotation();
local h8 = ChessPosition.new(8, 8):toNotation();
-- Expect to print "a1, h8".
print(a1, ", ", h8);
-- Prints "a1, h8" (tested in Studio)!
This functionally works, although Luau tosses a warning on line 36 (return self
, the final line within ChessPosition.new
's function body); that toNotation
does not exist in self
. So, I decided to commit a sin of sorts, and, well…
Try 2; lie to Luau and say it will all be okay.
It was time to do the unthinkable and cast to any
(shudder).
So, I rewrote the line to return self as any;
It had enough, clearly, as the warning became an error: Expected 'end' (to close 'function' at line 31), got 'as'
. A simple syntax error.
It’s very clear that type casting in the expression as type
syntax is not quite what I have to do. That being the case, how do I type cast in Luau?