Skip to main content

Overview

@field declares a class property. You can add an access level, a ? for nilable fields, and a description. Annotate fields you use often so GLuaLS can give better types and autocomplete.

Syntax

---@field [access] fieldName type [description]
---@field [access] fieldName? type [description]
---@field [access] [keyType] valueType [description]

Basic fields

Place @field annotations immediately after a @class line:
---@class User
---@field id number User ID
---@field name string Display name
---@field email string Email address
---@field createdAt string ISO timestamp

Optional fields

Add ? after the field name to mark it as nil sometimes:
---@class Player
---@field steamId string
---@field nickname? string Optional display name
---@field clan? string Optional clan tag
If you access an optional field without a nil check, GLuaLS reports need-check-nil when you enable strict nil checking.

Access control

Access modifiers do not change runtime behavior. GLuaLS checks them and can report diagnostics when code uses private or protected fields from the wrong place. Treat them as type and style rules, not runtime access control.
ModifierDescription
publicAccessible everywhere (default)
privateOnly accessible within class methods
protectedOnly accessible in the class and subclasses
packageOnly accessible within the same file/package
---@class MyClass
---@field public name string
---@field private m_count number
---@field protected m_parent MyClass?

Index-type fields

Use [keyType] syntax to define all keys of a type at once:
---@class Config
---@field [string] any Any string key maps to any value

---@class NumberIndex
---@field [number] Entity Array-style numeric indexing

Function fields

Fields can use function types:
---@class EventEmitter
---@field on fun(event: string, callback: fun(data: any)): nil
---@field emit fun(event: string, data: any): nil
---@field off fun(event: string): nil
Use this when code outside the Lua file adds the function, such as C++. If Lua defines the function, annotate the function itself to avoid duplicate definitions.

Tips and best practices

  • Place @field annotations directly after their @class declaration.
  • GLuaLS disables the inject-field diagnostic by default. Classes act as (partial), so you can define fields anywhere in the file. Fields are optional, but they improve type checking and autocomplete for the class.