Interfaces allow you to define the required structure of a table.
t.interface(definition)
Creates a checker based on a table of type checkers. Fields do not need to be present unless specified (use t.optional for clarity, though standard interfaces in t allow extra fields).
t.strictInterface(definition)
Similar to t.interface, but will fail if the table contains any fields not defined in the definition.
Example:
local IPlayer = t.interface({
Name = t.string,
Score = t.number,
})
local myPlayer = { Name = "TestPlayer", Score = 100 }
print(IPlayer(myPlayer)) --> true
local IPlayer = t.interface({
Name = t.string,
Score = t.number,
})
local myPlayer = { Name = "TestPlayer", Score = 100 }
print(IPlayer(myPlayer)) --> true
print(IPlayer({})) --> false, "[interface] bad value for Name: string expected, got nil"
-- Strict interface example
local IPlayerStrict = t.strictInterface({
Name = t.string,
Score = t.number,
})
print(IPlayerStrict({ Name = "Test", Score = 1, A = 1 })) --> false, "[interface] unexpected field 'A'"