Search code examples
luaroblox

Defining element type in a table


so when i define the type of a variable, it goes totally alright:

local Player: Player = nil

but when i try to define the type of an element in a table, it doesnt go exactly how i thought it would:

PlayerProfile.Player: Player = nil
Missed symbol `(`.Luau Syntax Check.(miss-symbol)

this is my first time working with type so anyone know the correct way of doing this?


Solution

  • You can't arbitrary set type to random table member in Luau. You need to set types for all members on table creation or inside its creation scope.

    On creation you can simply set type for each field directly:

    type PlayerProfile = {Player: SomeType, OtherField: SomeOtherType}
    

    Or you can express member types by first creating table with zero expression {} and assigning typed values to its members before leaving creation scope. But as soon as you leave that scope the table is "sealed" and no more changes are allowed.

    local PlayerProfile = {}
    PlayerProfile.Player = "string"
    PlayerProfile.SomeField = 123 -- number, types are inferred from initialization values