lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

Table type annotations

Open Dan-Crane opened this issue 1 month ago • 1 comments

Hello everyone.

I've defined a field as table<MyStates, BaseState>, but the analyzer doesn't complain when I assign a table with a completely different structure to it.

---@class BaseState
local BaseState = {}

---@enum MyStates
local States = {
    GAME = 1,
    GAME_OVER = 2,
}

---@class MyStateMachine
---@field private _states table<MyStates, BaseState>
local MyStateMachine = {}
MyStateMachine.__index = MyStateMachine

---@param states table<MyStates, BaseState>
function MyStateMachine:setStates(states)
    self._states = states
end

function tmp()
    -- Assigning a table with a different annotation directly. The analyzer doesn't complain.
    MyStateMachine._states = {
        ['kek'] = 69
    }
    -- Passing a table with a different annotation to a method. The analyzer doesn't complain.
    MyStateMachine:setStates({
        ['kek'] = 69,
    })
    -- The analyzer correctly complains about a number assignment.
    -- MyStateMachine._states = 69
    -- The analyzer correctly complains about passing a number.
    -- MyStateMachine:setStates(2)
end

As you can see, the type checker only seems to validate that the value is a table, but doesn't validate the internal key and value types for table<MyStates, BaseState>. Is this the expected behavior, or am I missing something? Is there a way to enforce stricter type checking for the contents of generic tables?

Dan-Crane avatar Nov 24 '25 04:11 Dan-Crane

similar issue: https://github.com/LuaLS/lua-language-server/issues/2610

Dan-Crane avatar Nov 24 '25 05:11 Dan-Crane