### Kakoune Setup: Plugin Installation (plug.kak) Source: https://luals.github.io/wiki/configuration Instructions for installing the kak-lsp plugin for Kakoune using plug.kak, including the command to build and install the plugin. ```dsconfig plug "kak-lsp/kak-lsp" do %{ cargo install --locked --force --path . } ``` -------------------------------- ### Neovim Setup: Basic Runtime Version Source: https://luals.github.io/wiki/configuration A minimal example for setting the runtime version of the lua-language-server in Neovim using the built-in LSP client. ```Lua require'lspconfig'.lua_ls.setup{ settings = { Lua = { runtime = { version = "LuaJIT" } } } } ``` -------------------------------- ### Kakoune Setup: Standalone Installation Source: https://luals.github.io/wiki/configuration Instructions for setting up kak-lsp when running standalone in Kakoune, ensuring the binary is in the PATH and configuring the session. ```cos evaluate-commands %sh{ kak-lsp --kakoune -s $kak_session } ``` -------------------------------- ### Neovim Setup: Luarocks and Workspace Library Source: https://luals.github.io/wiki/configuration An example for setting up lua-language-server in Neovim when using Luarocks, including specifying the runtime version and workspace library paths. ```Lua require'lspconfig'.lua_ls.setup{ settings = { Lua = { runtime = { version = 'Lua 5.3', path = { '?.lua', '?/init.lua', vim.fn.expand'~/.luarocks/share/lua/5.3/?.lua', vim.fn.expand'~/.luarocks/share/lua/5.3/?/init.lua', '/usr/share/5.3/?.lua', '/usr/share/lua/5.3/?/init.lua' } }, workspace = { library = { vim.fn.expand'~/.luarocks/share/lua/5.3', '/usr/share/lua/5.3' } } } } } ``` -------------------------------- ### Client Initialization Log Example (Lua Language Server) Source: https://luals.github.io/wiki/faq An example of a client initialization log message from the Lua Language Server. This log helps diagnose issues where the server might be scanning the wrong folder by examining the `rootUri` field. ```json [17:58:27.365][debug][#0:script\provider\client.lua:32]: Client init { capabilities = {... , }, clientInfo = { name = "Visual Studio Code - Insiders", version = "1.55.0-insider", }, locale = "zh-cn", processId = 21048, rootPath = "c:\\Users\\sumneko\.vscode-insiders\\extensions\\vscode-lua", rootUri = "file:///c%3A/Users/sumneko/.vscode-insiders/extensions/vscode-lua", trace = "off", workDoneToken = "a9e94178-eb6f-4277-ab21-6d81a5871041", workspaceFolders = { [1] = { name = "vscode-lua", uri = "file:///c%3A/Users/sumneko/.vscode-insiders/extensions/vscode-lua", }, }, } ``` -------------------------------- ### OnSetText Example - Lua Source: https://luals.github.io/wiki/plugins An example implementation of the OnSetText function in Lua. It checks for a specific prefix and processes the text to identify and format differences based on a pattern. ```Lua function OnSetText(uri, text) if text:sub(1, 4) ~= '--##' then return nil end local diffs = {} diffs[#diffs+1] = { start = 1, finish = 4, text = '', } for localPos, colonPos, typeName, finish in text:gmatch '()local%s+[%w_]+()%s*%:%s*([%w_]+)()' do diffs[#diffs+1] = { start = localPos, finish = localPos - 1, text = ('---@type %s\n'):format(typeName), } diffs[#diffs+1] = { start = colonPos, finish = finish - 1, text = '', } end return diffs end ``` -------------------------------- ### VM.OnCompileFunctionParam Example - Lua Source: https://luals.github.io/wiki/plugins An example implementation of VM.OnCompileFunctionParam in Lua. It demonstrates calling the default behavior and then attempting to match a pattern to assign a specific type to function parameters. ```Lua local nodeHelper = reuqire 'nodeHelper' -- Create pattern that already matches code in the form of `*.components.` local pattern = nodeHelper.createFieldPattern("*.components") function VM.OnCompileFunctionParam (next, func, param) -- Call the default if next(func, param) then return true -- If ready known the type, return true. Also you can continue end -- Try match pattern if nodeHelper.matchPattern(source, pattern) then -- Add a TestClass type to the parameters that match the pattern local type = vm.declareGlobal('type', 'TestClass', TESTURI) vm.setNode(source, vm.createNode(type, source)) return true end end ``` -------------------------------- ### Generate Documentation for Workspace Source: https://luals.github.io/wiki/usage Generates documentation from a specified workspace directory. The output files will be saved to the configured log path. ```shell --doc=C:/Users/Me/Documents/myLuaProject/ ``` -------------------------------- ### Specify Documentation Output Path Source: https://luals.github.io/wiki/usage Sets the directory where the generated documentation files should be placed. This flag works in conjunction with the `--doc` flag. ```shell --doc_out_path=C:/Users/Me/Documents/myLuaProjectDocumentation ``` -------------------------------- ### Lua ResolveRequire Custom Implementation Example Source: https://luals.github.io/wiki/plugins An example implementation of the ResolveRequire function. This function checks for a specific naming convention ('@' prefix) and returns a custom path for modules, otherwise returning nil for default resolution. ```lua ---@param uri string # The URI of file ---@param name string # Argument of require() ---@return string[]? function ResolveRequire(uri, name) -- Check if it's our custom name format if name:byte(1) ~= 0x40 then -- '@' at beginning return nil end -- Return path to real file location return { "file:///path/to/mods/" .. name:sub(2) .. "/main.lua" } ``` -------------------------------- ### Install libstdc++ on Fedora Linux Source: https://luals.github.io/wiki/build Installs the `libstdc++` package on Fedora Linux or similar distributions to resolve potential compile errors like `cannot find -lstdc++`. ```bash dnf install libstdc++-static ``` -------------------------------- ### Lua Print Debugging Example Source: https://luals.github.io/wiki/developing Demonstrates using the `print()` function to output information to stdout, which can be viewed in the VS Code OUTPUT panel. This is a simple method for quick debugging. ```lua local util = require 'utility' local client = require 'client' function OnSetText(uri, text) print(uri, #text, util.dump(client.info.clientInfo)) end ``` -------------------------------- ### Display Server Version Source: https://luals.github.io/wiki/usage Prints the current version of the Lua language server to the console and then exits the application. ```shell --version ``` -------------------------------- ### Kakoune Setup: Enabling LSP for Lua Files Source: https://luals.github.io/wiki/configuration Kakoune configuration to enable the language server protocol for Lua files and to ensure the LSP client exits when Kakoune terminates. ```awk ## Enable kak-lsp for Lua files hook global WinSetOption filetype=lua %{ lsp-enable-window } ## Close kak-lsp when kakoune is terminated hook global KakEnd .* lsp-exit ``` -------------------------------- ### Specify Configuration File Path Source: https://luals.github.io/wiki/usage Loads a specific configuration file for the server. If provided, external configurations (like from VS Code) will be ignored. ```shell --configpath=sumnekoLuaConfig.lua ``` -------------------------------- ### Allow Root Workspace Source: https://luals.github.io/wiki/usage Enables the use of the root or home directory as the workspace for the language server. ```shell --force-accept-workspace ``` -------------------------------- ### Set Metadata Output Path Source: https://luals.github.io/wiki/usage Defines the directory for generating standard Lua library definition files. The default location is './meta'. ```shell --metapath=D:/sumnekoLua/metaDefintions ``` -------------------------------- ### Perform Workspace Diagnosis Source: https://luals.github.io/wiki/usage Initiates a diagnostic check on the specified workspace. The results are written to the log path. ```shell --check=C:\Users\Me\path\to\workspace ``` -------------------------------- ### Lua Log Debugging Example Source: https://luals.github.io/wiki/developing Shows how to use the `log` function with different severity levels (trace, debug, info, warn, error, fatal) to record messages in a log file. This is useful for debugging plugins. ```lua local util = require 'utility' local client = require 'client' function OnSetText(uri, text) log.debug(uri, #text, util.dump(client.info.clientInfo)) end ``` -------------------------------- ### Lua type checking warning example Source: https://luals.github.io/wiki/type-checking Shows a basic example where the Lua language server detects a type change and issues a warning (e.g., 'cast-local-type'). ```lua local myString = "Hello World" myString = false ``` -------------------------------- ### Basic luarc.json Configuration Source: https://luals.github.io/wiki/configuration A fundamental example of a .luarc.json file. This file allows workspace-specific configurations for the Lua Language Server, such as specifying library paths, runtime versions, and disabling hints. It does not require the 'Lua.' prefix for settings. ```json { "$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json", "workspace.library": ["path/to/library/directory"], "runtime.version": "Lua 5.3", "hint.enable": false } ``` -------------------------------- ### config.json Example for Lua Addon Source: https://luals.github.io/wiki/addons This JSON file configures a Lua Language Server addon. It specifies the addon's name, Lua patterns for workspace and filename detection, and customizable settings for the language server or VS Code. ```json { // Name of the addon "name": "My Awesome Addon", // Lua string patterns to look for in a workspace. // If detected, this addon will be recommended to enable "words": [ "require[%s%(\"']+MAA[%)\"']" ], // Lua string patterns to look for in filenames. // If detected, this addon will be recommended to enable "files": ["my-awesome-file.lua"], // List of settings to apply when this addon is enabled "settings": { "Lua.diagnostics.globals" : [ "awesome" ] } } ``` -------------------------------- ### Lua Type Inference Example Source: https://luals.github.io/wiki/developing Shows an example of type inference in Lua, where the server determines the type of a variable (`x`) within a conditional block. This is handled by the `script/infer.lua` and `script/runner.lua` modules for type inference and tracking. ```lua --- ---@type number|nil local x if x then print(x) --> `x` is number here end ``` -------------------------------- ### Lua Array:fill() Method Source: https://luals.github.io/wiki/export-docs The 'fill' method populates the array with a specified value from a start index to an end index. It takes the value to fill with, an optional start index, and an optional stop index. If start or stop are omitted, they default to 0 and the array length respectively. The method returns the modified array. ```lua (method) Array:fill(value: any, start: integer, stop?: integer) -> Object: Array ``` -------------------------------- ### Lua dynamic typing example Source: https://luals.github.io/wiki/type-checking Demonstrates how a variable can change types multiple times in standard Lua, highlighting the need for a type checking system. ```lua local userInput = nil userInput = "Hello World!" userInput = 38 userInput = false ``` -------------------------------- ### Running the Lua Language Server Source: https://luals.github.io/wiki/usage Executes the Lua language server. The command differs slightly between Windows and Unix-based systems (macOS, Linux). If using the VS Code extension, this is handled automatically. ```batch .\bin\lua-language-server.exe ``` ```bash ./bin/lua-language-server ``` -------------------------------- ### Lua AST Parsing Example Source: https://luals.github.io/wiki/developing Demonstrates the structure of a Lua state object used for parsing and analyzing Lua code, including version, AST representation, errors, comments, and line mappings. It's part of the `script/parser` module. ```lua local state = { version = 'Lua 5.4', lua = [[local x = 1]], ast = { ... }, errs = { ... }, -- syntax errors comms = { ... }, -- comments lines = { ... }, -- map of offset and position } ``` -------------------------------- ### Set Server Locale Source: https://luals.github.io/wiki/usage Specifies the language used by the server. Available locales are located in the 'locale/' directory. ```shell --locale=zh-cn ``` -------------------------------- ### Set Log File Path Source: https://luals.github.io/wiki/usage Specifies the location where the server's log files should be written. If not provided, logs default to the './log' directory. ```shell --logpath=D:/luaServer/logs ``` -------------------------------- ### Communicate via TCP Socket Source: https://luals.github.io/wiki/usage Redirects server communication from standard input/output to a specified TCP port. ```shell --socket=5050 ``` -------------------------------- ### Lua Semantic Analysis Example Source: https://luals.github.io/wiki/developing Illustrates how Lua code, including type annotations, is analyzed and compiled into a node structure. This functionality is provided by `script/compiler.lua` and `script/runner.lua` for semantic analysis and variable tracking. ```lua --- ---@class myClass local mt ``` ```lua vm.compileNode('mt') --> node: { [1] = { type = 'local', [1] = 'mt', }, [2] = { type = 'global', cate = 'type', name = 'myClass', }, } ``` -------------------------------- ### Configure Logging Level Source: https://luals.github.io/wiki/usage Determines the verbosity of the server's logging. Higher levels (debug, trace) provide more detailed information useful for debugging. ```shell --loglevel=trace ``` -------------------------------- ### Array.fill Source: https://luals.github.io/wiki/export-docs The 'fill' method fills all the elements of an array from a start index to a stop index with a static value. It returns the modified array. ```APIDOC ## POST /array/fill ### Description Fills the array with a `value` from `start` to `stop` index. ### Method POST ### Endpoint /array/fill ### Parameters #### Request Body - **value** (any) - Required - The value to fill the array with. - **start** (integer) - Required - The index to start filling at. - **stop** (integer?) - Optional - The index to stop filling at. ### Request Example ```json { "value": 10, "start": 0, "stop": 5 } ``` ### Response #### Success Response (200) - **Array** (Array) - The modified array. #### Response Example ```json { "array": [10, 10, 10, 10, 10, 10] } ``` ``` -------------------------------- ### Lua: Using 'then' instead of 'do' in while loop Source: https://luals.github.io/wiki/syntax-errors Triggered when `then` is used instead of `do` to start the body of a `while` loop, which is a common syntax mistake. ```Lua err-do-as-then ``` -------------------------------- ### Lua: Missing minimum value in for loop Source: https://luals.github.io/wiki/syntax-errors Indicates that the minimum (start) value for a numeric `for` loop has not been provided. This is necessary for the loop to execute correctly. ```Lua miss-loop-min ``` -------------------------------- ### Set Check Diagnosis Level Source: https://luals.github.io/wiki/usage Filters the diagnostics reported by the `--check` flag. Only issues with priority equal to or higher than the specified level will be logged. ```shell --checklevel=Information ``` -------------------------------- ### Declare Function Version (Lua) Source: https://luals.github.io/wiki/annotations This example demonstrates how to specify the required Lua version for a function using the `@version` annotation. It indicates that the function requires a version greater than 5.2 and is compatible with JIT. ```lua ---@version >5.2, JIT function hello() end ``` -------------------------------- ### Lua Weak Union Check Example Source: https://luals.github.io/wiki/settings Illustrates the behavior of `type.weakUnionCheck`. If false, assigning a union type with a single matching type to a variable will cause an error. ```lua --@alias unionType string|boolean --@type string local str = false ``` -------------------------------- ### Declare Class Version (Lua) Source: https://luals.github.io/wiki/annotations This example shows how to define the required Lua version for a class using the `@version` annotation. It specifies that the `Entry` class requires Lua version 5.4. ```lua ---@version 5.4 ---@class Entry ``` -------------------------------- ### Map Special Variables in Lua Runtime Source: https://luals.github.io/wiki/settings Allows mapping 'special' variables to other identifiers, enabling custom behavior for certain keywords or functions. For example, mapping 'include' to 'require'. ```json {} ``` -------------------------------- ### Lua Weak Nil Check Example Source: https://luals.github.io/wiki/settings Demonstrates the effect of `type.weakNilCheck` on type casting. When false, assigning a union type including `nil` to a variable that does not permit `nil` will result in an error. ```lua --@alias unionType number|nil --@type number local num --@cast num unionType ``` -------------------------------- ### Lua Language Server LuaDocs API Reference Source: https://luals.github.io/wiki/export-docs This section lists the API functions that must be implemented in a custom script to override the default LuaDocs generation behavior. These functions handle tasks such as getting local paths, sorting documentation, processing source objects, gathering globals, and serializing the final documentation. ```lua export.getLocalPath(uri) -- Called when the documentation needs to get the path of a source relative to the DOC path. Returns the relative path, or the absolute path, prefixed with the string '[FOREIGN]' export.positionOf(rowcol) -- Wrapper for guide.positionOf(rowcol[1], rowcol[2]) export.sortDoc(a,b) -- A comparison function used by table.sort that is used to sort every piece of documentation in alphabetical order. export.documentObject(source, has_seen) -- A function that gets called on every source object. It is responsible for filtering each source to their corresponding export.makeDocObject[] function export.makeDocObject[] -- A table of functions that are responsible for building their corresponding 's documentation. TYPES include 'type', 'variable', 'doc.class', etc. 'INIT' corresponds to every documentation object before it is processed by its corresponding type. export.gatherGlobals() -- Called when the documentation needs an exhaustive list of the globals it should export documentation. By default this includes the result of vm.getAllGlobals(). Returns the collected variables/types. export.makeDocs(globals, callback) -- Documents globals from export.gatherGlobals() by calling export.documentObject on each one; updates its progress by calling callback when a global is finished being documented. Returns a table of the collected documentation export.serializeAndExport(docs, outputDir) -- Serializes documentation tables from export.makeDocs to json and markdown, Writes them to /doc.json and /doc.md, respectively. Returns these paths. ``` -------------------------------- ### Lua: Fill Array with Value Source: https://luals.github.io/wiki/export-docs The `fill` method populates an array with a specified value within a given range of indices. It takes the value to fill, a starting index, and an optional ending index as parameters. The method returns the modified array. ```Lua (method) Array:fill(value: any, start: integer, stop?: integer) -> Object: Array Fills the array with a `value` from `start` to `stop` @_param_ `value` — The value to fill the array with @_param_ `start` — The index to start filling at @_param_ `stop` — The index to stop filling at ``` -------------------------------- ### Prevent Ignoring Function Return Values (@nodiscard) Source: https://luals.github.io/wiki/annotations The @nodiscard annotation marks a function to ensure its return values are not ignored. If ignored, a warning will be raised, guiding users to capture the function's output. ```Lua --@return string username --@nodiscard function getUsername() end ``` -------------------------------- ### Kakoune LSP Configuration (kak-lsp.toml) Source: https://luals.github.io/wiki/configuration Configuration for kak-lsp.toml to inform it about the lua-language-server, including filetypes, roots, and the command to execute. ```toml [language.lua] filetypes = ["lua"] roots = [".git/"] command = "lua-language-server" ``` -------------------------------- ### Clone Lua Language Server Repository Source: https://luals.github.io/wiki/build Clones the Lua Language Server repository from GitHub to your local machine. ```bash git clone https://github.com/LuaLS/lua-language-server cd lua-language-server ``` -------------------------------- ### Build Lua Language Server Source: https://luals.github.io/wiki/build Provides build commands for the Lua Language Server on different operating systems. Includes commands for Windows, macOS, and Linux. ```cmd .\make.bat ``` ```bash ./make.sh ``` -------------------------------- ### Custom Lua Configuration with Key-Value Pairs Source: https://luals.github.io/wiki/configuration Shows an alternative Lua configuration format using string keys to represent nested settings. This approach flattens the structure for easier key access. ```lua return { ["Lua.runtime.version"] = "Lua 5.1" } ``` -------------------------------- ### Lua: Using 'do' instead of 'then' in if statement Source: https://luals.github.io/wiki/syntax-errors Triggered when `do` is used instead of `then` to start the block of an `if` statement. This is a common mistake in conditional syntax. ```Lua err-then-as-do ``` -------------------------------- ### Exclude Directories with workspace.ignoreDir Source: https://luals.github.io/wiki/faq Optimize startup speed by excluding unnecessary directories. This setting reduces the number of files the server needs to process during initialization, leading to faster startup times. It is particularly useful in projects with large or irrelevant directories. ```lua workspace.ignoreDir = { "path/to/exclude", "another/directory" } ``` -------------------------------- ### Combined Lua Configuration (Nested and Key-Value) Source: https://luals.github.io/wiki/configuration Illustrates a mixed Lua configuration file combining nested tables and string keys. This allows for flexible configuration by mixing different structural approaches. ```lua return { Lua = { runtime = { version = "Lua 5.1" }, ["completion.enable"] = false } } ``` -------------------------------- ### VS Code/coc.nvim Configuration Source: https://luals.github.io/wiki/configuration Configuration for the lua-language-server within VS Code or coc.nvim, specifying command, root patterns, and various Lua settings like workspace library, runtime version, and diagnostics. ```JSON { // Unrelated settings... "languageserver": { "lua": { "cwd": "full path to lua-language-server directory", "command": "full path to lua-language-server executable", "filetypes": ["lua"], "rootPatterns": [".git/"] } }, "settings": { "Lua": { "workspace": { "library": [ "/path/to/hammerspoon-completion/build/stubs", "/path/to/neovim/runtime/lua" ], "maxPreload": 2000, "preloadFileSize": 1000 }, "runtime": { "version": "Lua 5.4" }, "diagnostics": { "enable": true, "globals": ["hs", "vim", "it", "describe", "before_each", "after_each"], "disable": ["lowercase-global"] }, "completion": { "keywordSnippet": "Disable" } } } } ``` -------------------------------- ### Configure Lua Runtime Path for Require Source: https://luals.github.io/wiki/settings Defines the search paths for the `require` function. Allows specifying file patterns and directory structures for module loading. Supports workspace-relative paths and library loading for external modules. ```json [ "?.lua", "?/init.lua" ] ``` -------------------------------- ### Directory Structure for Lua Addons Source: https://luals.github.io/wiki/addons Illustrates the expected file and directory structure for organizing Lua addons. This includes a root addon directory, a 'library' folder for definitions, and configuration/plugin files. ```plaintext 📂 LuaAddons/ ├── 📂 Addon1/ │ ├── 📁 library/ │ ├── 📜 config.json │ └── 📜 plugin.lua └── 📂 Addon2/ ├── 📁 library/ └── 📜 config.json ``` -------------------------------- ### Default Lua Configuration for Code Formatting Source: https://luals.github.io/wiki/formatter This Lua snippet demonstrates the default configuration for code formatting in custom Lua environments, often used with Neovim. It enables formatting and sets indentation style and size. ```Lua Lua = { format = { enable = true, -- Put format options here -- NOTE: the value should be String! defaultConfig = { indent_style = "space", indent_size = "2", } }, } ``` -------------------------------- ### Kakoune LSP Server Settings (kak-lsp.toml) Source: https://luals.github.io/wiki/configuration Configuration within kak-lsp.toml to define server-specific settings for the Lua language, such as diagnostics severity and runtime version. ```toml [language.lua.settings] Lua.diagnostics.severity.undefined-global = "Error" Lua.runtime.version = "Lua 5.2" Lua.telemetry.enable = false ``` -------------------------------- ### Custom Lua Configuration File Structure Source: https://luals.github.io/wiki/configuration Demonstrates a custom configuration file written in Lua, using nested tables to define settings. This format allows for organized configuration of LuaLS features. ```lua return { Lua = { runtime = { version = "Lua 5.1" } } } ``` -------------------------------- ### Locate Lua Language Server Log Files Source: https://luals.github.io/wiki/faq Provides the file paths to find the Lua Language Server's log files across different operating systems and IDEs (Windows, WSL, Linux/macOS, VS Code). Remember to replace 'X.X.X' with the actual extension version. ```plaintext %homepath%\.vscode\extensions\sumneko.lua-X.X.X\server\log\ ``` ```plaintext \\wsl$\\Ubuntu-20.04\home\USERNAME\.vscode-server\extensions\sumneko.lua-X.X.X\server\log\ ``` ```plaintext ~/.vscode/extensions/sumneko.lua-X.X.X/server/log/ ``` ```plaintext /path/to/lua-language-server/log/ ``` ```plaintext sumneko_lua/log/ ``` -------------------------------- ### Create Lua Definition File for a Class Source: https://luals.github.io/wiki/definition-files This snippet demonstrates how to create a definition file for a Lua class named 'Character'. It includes the essential `@meta` annotation and defines a class with a `hello` function that accepts a string parameter. ```lua --- ---@meta ---@class Character Character = {} ---@param name string function Character.hello(name) print("Hello " .. name .. "!") end ``` -------------------------------- ### Configure Documentation Regex Engine Source: https://luals.github.io/wiki/settings Selects the regular expression engine for matching documentation scope names. Options are 'glob' for simple glob patterns or 'lua' for full Lua-style regular expressions. ```json { "doc.regengine": "glob" } ``` -------------------------------- ### Anatomy of a Lua Language Server Addon Source: https://luals.github.io/wiki/addons Defines the typical file and directory structure for creating a new Lua Language Server addon. It highlights the 'library' directory for definitions, a 'plugin.lua' for custom logic, and a 'config.json' for addon-specific settings. ```plaintext 📂 myAddon/ ├── 📁 library/ │ ├── 📜 http.lua │ └── 📜 error.lua ├── 📜 plugin.lua └── 📜 config.json ``` -------------------------------- ### Define Lua Runtime Folder Naming Template Source: https://luals.github.io/wiki/settings Sets the template for naming generated definition folders, incorporating version, language, and encoding. The default template is "${version} ${language} ${encoding}". ```shell "${version} ${language} ${encoding}" ``` -------------------------------- ### Configure Workspace Diagnostic Rate Source: https://luals.github.io/wiki/settings Determines the processing speed for workspace diagnostics as a percentage. A rate of 100% allows for the fastest diagnosis, while lower rates reduce CPU usage at the cost of slower analysis. ```json { "diagnostics.workspaceRate": 100 } ``` -------------------------------- ### Configure Lua Language Server Workspace Settings Source: https://luals.github.io/wiki/addons Shows how to update the Lua Language Server configuration to include a path to a directory containing custom addons. This setting, 'Lua.workspace.userThirdParty', informs the server where to find user-added definitions and plugins. ```json { "Lua.workspace.userThirdParty": ["C:\\Users\\me\\Documents\\LuaAddons"] } ``` -------------------------------- ### VS Code Debugger Configuration for Lua Language Server Source: https://luals.github.io/wiki/developing Provides the necessary JSON configuration for `settings.json` in VS Code to enable debugging the Lua Language Server. It specifies development mode and the debug port. ```json "Lua.misc.parameters": [ "--develop=true", "--dbgport=11428" ], ``` -------------------------------- ### Semantic Token Mappings in Lua Source: https://luals.github.io/wiki/developing This table outlines the mapping between semantic token types and their corresponding syntax token representations in Lua. These mappings are crucial for code highlighting and understanding in development environments. ```markdown semantic token| fallen syntax token| preview ---|---|--- `namespace.static`| `support.function.lua`| `namespace.readonly`| `constant.language.lua`| `namespace.deprecated`| `entity.name.label`| `parameter.declaration`| `variable.parameter`| `property.declaration`| `entity.other.attribute`| `variable`| `variable.other.lua`| `interface.declaration`| `entity.name.function.lua`| ``` -------------------------------- ### Configure Library Files Diagnosis Source: https://luals.github.io/wiki/settings Determines how files loaded via workspace.library are diagnosed. Choices are to always diagnose, only when open, or never. ```lua -- Set how files loaded with workspace.library are diagnosed. -- Options: "Enable", "Opened", "Disable" "Opened" ``` -------------------------------- ### Provide Arguments to Lua Runtime Plugin Source: https://luals.github.io/wiki/settings An array of strings representing additional arguments passed to the active Lua runtime plugin. Defaults to an empty array. ```json [] ``` -------------------------------- ### Simulate Lua 'Require' a File Source: https://luals.github.io/wiki/annotations Simulates the `require` function in Lua. This annotation allows the language server to understand module dependencies and provide analysis as if the file were actually required. ```Lua ---@module 'http' --The above provides the same as require 'http' --within the language server ``` -------------------------------- ### Configure Diagnostic File Status (Lua) Source: https://luals.github.io/wiki/settings Sets the file status required for each diagnostic group to apply. This is an object mapping diagnostic group names to file states ('Any', 'Opened', 'None', 'Fallback'). 'Fallback' allows individual control via `diagnostics.neededFileStatus`. ```json { "ambiguity": "Fallback", "await": "Fallback", "codestyle": "Fallback", "duplicate": "Fallback", "global": "Fallback", "luadoc": "Fallback", "redefined": "Fallback", "strict": "Fallback", "strong": "Fallback", "type-check": "Fallback", "unbalanced": "Fallback", "unused": "Fallback" } ``` -------------------------------- ### Configure Workspace Library with Definition Files Source: https://luals.github.io/wiki/definition-files This configuration snippet shows how to set the `workspace.library` in LuaLS to include custom definition files. It assumes the definition files are located in a specific directory or are individual files. The path provided will be scanned by LuaLS for type information. ```json { "Lua.workspace.library": [ "/path/to/your/definition/files", "/path/to/another/definition/file.lua" ] } ``` -------------------------------- ### Configure Documentation Package Name Patterns Source: https://luals.github.io/wiki/settings Specifies patterns for identifying table field names that should be treated as package-private. Fields matching these patterns will be considered internal to the package. ```json { "doc.packageName": [ "_private*" ] } ``` -------------------------------- ### Default JSON Configuration for Lua Formatting Source: https://luals.github.io/wiki/formatter This JSON snippet shows the default configuration for Lua code formatting, commonly used in Visual Studio Code's settings.json or .luarc.json files. It specifies indentation style and size. ```JSON { "Lua.format.defaultConfig": { "indent_style": "space", "indent_size": "2" } } ``` -------------------------------- ### Lua type checking with annotations Source: https://luals.github.io/wiki/type-checking Illustrates how to use Lua annotations (like `@param` and `@return`) to provide type information to the language server for more accurate diagnostics, preventing type errors in function calls. ```lua local settings = {} ---@param settingName string The name of the setting to set the value of ---@param value any The value of this setting ---@return boolean success If the setting's value was changed successfully function settings.set(settingName, value) end settings.set(0, false) ``` -------------------------------- ### OnSetText Function Definition - Lua Source: https://luals.github.io/wiki/plugins Defines the OnSetText function which receives the URI and text of an edited file. It should return a list of differences to be written to 'diffed.lua'. Dependencies include the 'diff' class definition. ```Lua --@class diff ---@field start integer # The number of bytes at the beginning of the replacement ---@field finish integer # The number of bytes at the end of the replacement ---@field text string # What to replace ---@param uri string # The uri of file ---@param text string # The content of file ---@return nil|diff[] function OnSetText(uri, text) end ``` -------------------------------- ### Specify Lua Runtime Plugin Path Source: https://luals.github.io/wiki/settings Sets the path to an external plugin used by the Lua runtime. Defaults to an empty string to prevent unintentional code execution. ```shell "" ``` -------------------------------- ### Configure Workspace Diagnostic Delay Source: https://luals.github.io/wiki/settings Sets the delay in milliseconds before re-diagnosing the workspace after a file event. A negative value disables automatic workspace diagnostics. ```json { "diagnostics.workspaceDelay": 3000 } ``` -------------------------------- ### Configure Needed File Status for Diagnostics Source: https://luals.github.io/wiki/settings Defines the file status for various diagnostic groups. This impacts whether diagnostics are applied to any loaded file, only opened files, or disabled entirely. ```json { "ambiguity-1": "Any", "assign-type-mismatch": "Opened", "await-in-sync": "None", "cast-local-type": "Opened", "cast-type-mismatch": "Any", "circle-doc-class": "Any", "close-non-object": "Any", "code-after-break": "Opened", "codestyle-check": "None", "count-down-loop": "Any", "deprecated": "Any", "different-requires": "Any", "discard-returns": "Any", "doc-field-no-class": "Any", "duplicate-doc-alias": "Any", "duplicate-doc-field": "Any", "duplicate-doc-param": "Any", "duplicate-index": "Any", "duplicate-set-field": "Opened", "empty-block": "Opened", "global-elements": "None", "global-in-nil-env": "Any", "incomplete-signature-doc": "None", "inject-field": "Opened", "invisible": "Any", "lowercase-global": "Any", "missing-fields": "Any", "missing-global-doc": "None", "missing-local-export-doc": "None", "missing-parameter": "Any", "missing-return": "Any", "missing-return-value": "Any", "name-style-check": "None", "need-check-nil": "Opened", "newfield-call": "Any", "newline-call": "Any", "no-unknown": "None", "not-yieldable": "None", "param-type-mismatch": "Opened", "redefined-local": "Opened", "redundant-parameter": "Any", "redundant-return": "Opened", "redundant-return-value": "Any", "redundant-value": "Any", "return-type-mismatch": "Opened", "spell-check": "None", "trailing-space": "Opened", "unbalanced-assignments": "Any", "undefined-doc-class": "Any", "undefined-doc-name": "Any", "undefined-doc-param": "Any", "undefined-env-child": "Any", "undefined-field": "Opened", "undefined-global": "Any", "unknown-cast-variable": "Any", "unknown-diag-code": "Any", "unknown-operator": "Any", "unreachable-code": "Opened", "unused-function": "Opened", "unused-label": "Opened", "unused-local": "Opened", "unused-vararg": "Opened" } ``` -------------------------------- ### Simulate Lua 'Require' and Assign to Variable Source: https://luals.github.io/wiki/annotations Simulates requiring a file in Lua and assigning the result to a variable. This helps the language server track module usage and variable assignments. ```Lua ---@module 'http' local http --The above provides the same as local http = require 'http' --within the language server ``` -------------------------------- ### Set Lua Runtime Version Source: https://luals.github.io/wiki/settings Specifies the Lua runtime version to be used. Options include Lua 5.1, 5.2, 5.3, 5.4, and LuaJIT. ```json "Lua 5.4" ``` -------------------------------- ### Select Locale via Command Line Source: https://luals.github.io/wiki/translations Manually set the locale for the Lua Language Server using the `--locale` flag. This is useful for testing or specifying a preferred language. ```bash lua-language-server --locale ``` -------------------------------- ### Enable Code Style Checking in LuaLS Diagnostics Source: https://luals.github.io/wiki/formatter This configuration snippet enables code style checking for LuaLS projects. It requires adding an entry to the `diagnostics.neededFileStatus` setting, specifying that 'codestyle-check' should be applied to any file status. This is typically done within a configuration file. ```json ["codestyle-check"] = "Any" ``` -------------------------------- ### Lua ResolveRequire Function Signature Source: https://luals.github.io/wiki/plugins Defines the signature for the ResolveRequire function. It accepts the URI of a file and the name used in require(), returning an optional array of strings representing resolved paths. ```lua ---@param uri string # The URI of file ---@param name string # Argument of require() ---@return string[]? function ResolveRequire(uri, name) end ``` -------------------------------- ### Lua Addon Path Configuration Source: https://luals.github.io/wiki/settings Specifies how to configure the `workspace.userThirdParty` setting in LuaLS. This setting expects an array of strings, where each string is a path to a directory containing custom addons. The path should point to the root directory of your addons, not a specific addon file. ```plaintext 📦 myLuaLibraries/ ├── 📂 myAddon/ │ ├── 📂 library/ │ └── 📜 config.lua └── 📂 anotherAddon/ ├── 📂 library/ └── 📜 config.lua ``` -------------------------------- ### Configure Workspace Diagnostic Events Source: https://luals.github.io/wiki/settings Specifies when workspace diagnostics should be triggered. Options include 'OnChange' for immediate analysis after changes, 'OnSave' for analysis upon saving files, or 'None' to disable automatic triggering. ```json { "diagnostics.workspaceEvent": "OnSave" } ``` -------------------------------- ### Add Support for Non-Standard Lua Symbols Source: https://luals.github.io/wiki/settings Enables support for non-standard symbols in Lua code, allowing for custom operators and keywords. Users should verify runtime support for these symbols. ```json [ "//", "/**/", "\"\"", "+=", "-=", "*=", "/=", "%%=", "^=", "//=", "|=", "&=", "<<=", ">>=", "||", "&&", "!", "!=", "continue" ] ``` -------------------------------- ### Lua: Different requires for the same file Source: https://luals.github.io/wiki/diagnostics This diagnostic flags situations where a file is required using different names, often due to being included from different directory structures within a project. It helps identify potential confusion or redundancy in module loading. ```Lua -- main.lua local strings = require("helpers.strings") local pretty = require("helpers.pretty") ``` ```Lua -- helpers/pretty.lua local strings = require("strings") ```