### CI/CD Workflow for Documentation Generation Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_doc_cli/README.md An example GitHub Actions workflow to automate the installation of the CLI, generation of documentation, and potentially deployment. This ensures documentation is always up-to-date. ```yaml name: Generate and Deploy Docs on: push: branches: - main jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - name: Install emmylua_doc_cli run: cargo install emmylua_doc_cli - name: Generate Docs run: emmylua_doc_cli ./src -o ./docs --site-name "My Project" ``` -------------------------------- ### EmmyLua Path Rules Configuration Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/config/emmyrc_json_EN.md Example demonstrating various path rule syntaxes for workspace and resource configurations. ```json { "workspace": { "library": [ "${workspaceFolder}/types", "{env:HOME}/.lua", "{luarocks}" ], "workspaceRoots": [ "./src", "./test" ] } } ``` -------------------------------- ### Full EmmyLua Configuration Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/config/emmyrc_json_EN.md A comprehensive example of the .emmyrc.json configuration, covering all available options. ```json { "$schema": "https://raw.githubusercontent.com/EmmyLuaLs/emmylua-analyzer-rust/refs/heads/main/crates/emmylua_code_analysis/resources/schema.json", "codeAction": { "insertSpace": null }, "codeLens": { "enable": true }, "completion": { "enable": true, "autoRequire": true, "autoRequireFunction": "require", "autoRequireNamingConvention": "keep", "autoRequireSeparator": ".", "callSnippet": false, "postfix": "@", "baseFunctionIncludesName": true }, "diagnostics": { "enable": true, "disable": [], "enables": [], "globals": [], "globalsRegex": [], "severity": {}, "diagnosticInterval": 500 }, "doc": { "privateName": [], "knownTags": [], "syntax": "md" }, "documentColor": { "enable": true }, "format": { "externalTool": null, "externalToolRangeFormat": null, "useDiff": false }, "hint": { "enable": true, "paramHint": true, "indexHint": true, "localHint": true, "overrideHint": true, "metaCallHint": true, "enumParamHint": false }, "hover": { "enable": true, "customDetail": null }, "inlineValues": { "enable": true }, "references": { "enable": true, "fuzzySearch": true, "shortStringSearch": false }, "resource": { "paths": [] }, "runtime": { "version": "LuaLatest", "requireLikeFunction": [], "frameworkVersions": [], "extensions": [], "requirePattern": [], "nonstandardSymbol": [], "special": {} }, "semanticTokens": { "enable": true, "renderDocumentationMarkup": true }, "signature": { "detailSignatureHelper": true }, "strict": { "requirePath": false, "typeCall": false, "arrayIndex": true, "metaOverrideFileDefine": true, "docBaseConstMatchBaseType": true, "requireExportGlobal": false }, "workspace": { "ignoreDir": [], "ignoreGlobs": [], "library": [], "packageDirs": [], "workspaceRoots": [], "preloadFileSize": 0, "encoding": "utf-8", "moduleMap": [], "reindexDuration": 5000, "enableReindex": false } } ``` -------------------------------- ### Example Configuration for Stylua Formatter Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/external_format/external_formatter_options_EN.md This example demonstrates a comprehensive configuration for the Stylua formatter, covering both document and range formatting with various options. ```json { "format" : { "externalTool": { "program": "stylua", "args": [ "-", "--stdin-filepath", "${file}", "--indent-width=${indent_size}", "--indent-type", "${use_tabs?Tabs:Spaces}" ] }, "externalToolRangeFormat": { "program": "stylua", "args": [ "-", "--stdin-filepath", "${file}", "--indent-width=${indent_size}", "--indent-type", "${use_tabs?Tabs:Spaces}", "--range-start=${start_offset}", "--range-end=${end_offset}" ], "timeout": 5000 } } } ``` -------------------------------- ### Install EmmyLua Language Server Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_ls/README.md Use Cargo to install the emmylua_ls binary. This command is used for setting up the language server. ```shell cargo install emmylua_ls ``` -------------------------------- ### Usage Examples Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/return.md Demonstrates how to call functions with various return types and how to handle the returned values. ```lua -- Usage examples local name = getCurrentUserName() local result = calculate(10, 20) local success, message = validateInput("test") if success then print("Validation successful:", message) end local user, error = findUserById(123) if user then print("Found user:", user.name) else print("Error:", error) end local queryResult = queryUsers({status = "active"}) print("Found", queryResult.count, "users") -- Using iterator for id, userName in iterateUsers() do print(id, userName) end ``` -------------------------------- ### Usage Example: Configuration Object Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Demonstrates creating a 'Configuration' object, utilizing both direct fields and index signature fields. ```lua -- Usage examples ---@type Configuration local config = { host = "localhost", port = 8080, database = "myapp", -- Supported through index signature cache = true -- Supported through index signature } ``` -------------------------------- ### Usage Examples for Overloaded Functions Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/overload.md Provides concrete examples demonstrating how to call the previously defined overloaded functions ('add', 'toString', 'Vector.new', 'apiRequest') with different argument combinations. ```lua -- Usage examples local result1 = add(5) -- Uses overload fun(x: number): number local result2 = add(5, 10) -- Uses overload fun(x: number, y: number): number local result3 = add(5, 10, 15) -- Uses overload fun(x: number, y: number, z: number): number local str1 = toString(42) -- Uses overload fun(value: number): string local str2 = toString("hello") -- Uses overload fun(value: string): string local str3 = toString(true) -- Uses overload fun(value: boolean): string local vec1 = Vector.new() -- Uses overload fun(): Vector local vec2 = Vector.new(1) -- Uses overload fun(x: number): Vector local vec3 = Vector.new(1, 2) -- Uses overload fun(x: number, y: number): Vector local vec4 = Vector.new(1, 2, 3) -- Uses overload fun(x: number, y: number, z: number): Vector local response1 = apiRequest("/users") local response2 = apiRequest("/users", {method = "POST"}) local response3 = apiRequest("/users", {name = "John"}) local response4 = apiRequest("/users", {name = "John"}, {method = "POST"}) ``` -------------------------------- ### Usage Examples of Enumerations Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/enum.md Provides practical examples of how to use defined enumerations in variable assignments and function calls. ```lua -- Usage examples local response = { status = HTTPStatus.OK, data = {message = "Hello World"} } print(getStatusMessage(response.status)) writeLog(LogLevel.INFO, "Application started") writeLog(LogLevel.ERROR, "Database connection failed") local currentUser = { id = 1001, name = "John", permissions = { [Permission.READ] = true, [Permission.WRITE] = true } } if hasPermission(currentUser, Permission.WRITE) then print("User can write") end ``` -------------------------------- ### Flat layout example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_formatter/tutorial_EN.md Demonstrates a simple table formatted in a flat, single-line layout when possible. ```lua local point = { x = 1, y = 2 } ``` -------------------------------- ### Install EmmyLua Analyzer Tools via Cargo Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Install the language server, static analyzer/linter, and documentation generator using Cargo. Ensure these binaries are in your system's PATH for editor integration. ```bash cargo install emmylua_ls # Language server cargo install emmylua_check # Static analyzer / linter cargo install emmylua_doc_cli # Documentation generator ``` -------------------------------- ### Lua File System Path Completion Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/features/features_EN.md Shows how the language server detects path strings and provides file system completion. ```lua "./config/settings.lua" ``` -------------------------------- ### Usage Example: User Object Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Provides a concrete example of creating a 'User' object based on the defined `@field` annotations. ```lua -- Usage examples ---@type User local user = { id = 1001, name = "John", email = "john@example.com", createdAt = "2024-01-01" } ``` -------------------------------- ### Lua Module Path Completion Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/features/features_EN.md Demonstrates smart completion for require parameters, supporting both dot and slash separators. ```lua require("utils.string") ``` -------------------------------- ### Install emmylua_doc_cli via Cargo Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_doc_cli/README.md Use this command to install the tool using the Rust package manager, Cargo. Ensure you have Rust and Cargo installed. ```shell cargo install emmylua_doc_cli ``` -------------------------------- ### Progressive fill layout example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_formatter/tutorial_EN.md Shows how function arguments are progressively filled into new lines for compact multi-line output. ```lua some_function( first_arg, second_arg, third_arg, fourth_arg ) ``` -------------------------------- ### Start emmylua_ls with TCP Mode Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Manually start the emmylua_ls server using TCP mode for remote or debug-friendly setups. Specify the IP address and port for the connection. ```bash emmylua_ls -c tcp --ip 127.0.0.1 --port 5007 ``` -------------------------------- ### EmmyLua Formatter Configuration Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_formatter/README.md An example TOML configuration file for the EmmyLua formatter, showcasing settings for syntax, indentation, layout, output, spacing, comments, EmmyDoc alignment, and general alignment. ```toml [syntax] level = "Lua55" [indent] kind = "Space" width = 4 [layout] max_line_width = 100 max_blank_lines = 1 table_expand = "Auto" call_args_expand = "Auto" func_params_expand = "Auto" [output] insert_final_newline = true trailing_comma = "Never" trailing_table_separator = "Inherit" quote_style = "Preserve" single_arg_call_parens = "Preserve" simple_lambda_single_line = "Preserve" end_of_line = "LF" [spacing] space_before_call_paren = false space_before_func_paren = false space_inside_braces = true space_inside_parens = false space_inside_brackets = false space_around_math_operator = true space_around_concat_operator = true space_around_assign_operator = true [comments] align_line_comments = true align_in_statements = false align_in_table_fields = true align_in_call_args = true align_in_params = true align_across_standalone_comments = false align_same_kind_only = false space_after_comment_dash = true line_comment_min_spaces_before = 1 line_comment_min_column = 0 [emmy_doc] align_tag_columns = true align_declaration_tags = true align_reference_tags = true align_multiline_alias_descriptions = true space_between_tag_columns = false space_after_description_dash = true [align] continuous_assign_statement = false table_field = true ``` -------------------------------- ### Input JSON Schema Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/schema_to_emmylua/README.md An example of a JSON schema file that can be converted into EmmyLua annotations. ```json { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" }, "tags": { "type": "array", "items": { "type": "string" } } }, "required": ["name"] } ``` -------------------------------- ### API Client Meta Definitions (HTTP Client) Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/meta.md Example of @meta annotations for an API client, defining an 'HTTPClient' class with methods like 'get' and 'post'. ```APIDOC ---@meta http_client ---@class HTTPClient local HTTPClient = {} ---@param url string Request URL ---@param options? {headers?: table, timeout?: number} ---@return {status: number, body: string, headers: table} function HTTPClient.get(url, options) end ---@param url string Request URL ---@param data table Request body ---@param options? {headers?: table, timeout?: number} ---@return {status: number, body: string, headers: table} function HTTPClient.post(url, data, options) end return HTTPClient ``` -------------------------------- ### Basic Documentation Generation Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_doc_cli/README.md Generate documentation for Lua files in a specified directory and output it to a default location. This is the simplest way to start generating docs. ```shell emmylua_doc_cli ./src -o ./docs ``` -------------------------------- ### Install schema_to_emmylua via Cargo Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/schema_to_emmylua/README.md Install the tool using the Rust package manager Cargo. This command is used for building the tool from source. ```bash cargo install schema_to_emmylua ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/CONTRIBUTING.md Install pre-commit hooks to automatically run checks before each commit. This is an optional step for developers who wish to enforce code style and quality checks locally. ```shell pre-commit install ``` -------------------------------- ### Inheritance Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/class.md Shows how to implement single inheritance by defining a 'Dog' class that extends the 'Animal' class, overriding the 'speak' method. ```lua -- Inheritance example ---@class Dog : Animal ---@field breed string Breed ---@field isVaccinated boolean Whether vaccinated local Dog = setmetatable({}, {__index = Animal}) function Dog:speak() print(self.name .. " barks: Woof!") end ---@param name string ---@param breed string ---@param age number ---@return Dog function Dog.new(name, breed, age) local self = Animal.new(name, "Canine", age) self.breed = breed self.isVaccinated = false return setmetatable(self, {__index = Dog}) end ``` -------------------------------- ### Install emmylua_check via Cargo Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_check/README.md Install the emmylua_check tool using the cargo package manager. ```shell cargo install emmylua_check ``` -------------------------------- ### Usage Example: ScoreBoard Object Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Illustrates creating a 'ScoreBoard' object, populated using string keys as defined by the index signature. ```lua -- Usage examples ---@type ScoreBoard local scores = { ["John"] = 95, ["Jane"] = 87, ["Bob"] = 92 } ``` -------------------------------- ### Main Async Function Usage Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/async.md An example of an asynchronous main function that orchestrates calls to other asynchronous operations like fetching data, reading/writing files, querying a database, and performing safe operations. ```lua ---@async function main() -- Fetch data asynchronously local data = fetchData("https://api.example.com/users") print("Received:", data) -- Read file asynchronously local content = readFileAsync("config.txt") print("File content:", content) -- Write file asynchronously local success = writeFileAsync("output.txt", "Hello, World!") if success then print("File written successfully") end -- Query database asynchronously local users = queryDatabase("SELECT * FROM users") for _, user in ipairs(users) do print("User:", user.name) end -- Handle async operation with error handling local success, error = safeAsyncOperation("normal") if not success then print("Error:", error) end end -- Start the async main function main() ``` -------------------------------- ### Generated EmmyLua Annotations Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/schema_to_emmylua/README.md The resulting EmmyLua annotations generated from the input JSON schema example. ```lua --@class Person --@field public name string --@field public age integer|nil --@field public tags string[]|nil ``` -------------------------------- ### Access Control Field Examples Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Shows examples of fields with different access control modifiers (public, private, protected, package) for a 'BankAccount' class. ```lua -- Access control examples ---@class BankAccount ---@field public accountNumber string Account number ---@field public balance number Account balance ---@field private pin string PIN code ---@field protected accountType string Account type ---@field package internalId number Internal ID ``` -------------------------------- ### Recommended EmmyLua Template Configuration Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/config/emmyrc_json_EN.md A recommended starting template for most Lua projects, including completion and diagnostics settings. ```json { "$schema": "https://raw.githubusercontent.com/EmmyLuaLs/emmylua-analyzer-rust/refs/heads/main/crates/emmylua_code_analysis/resources/schema.json", "completion": { "autoRequire": true, "callSnippet": false, "postfix": "@" }, "diagnostics": { "globals": [], "disable": ["undefined-global"] }, "doc": { "syntax": "md" }, "runtime": { "version": "LuaLatest", "requirePattern": ["?.lua", "?/init.lua"] } } ``` -------------------------------- ### Basic Class Definition Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/class.md Defines a basic 'Animal' class with fields and a constructor, demonstrating simple class creation in Lua. ```lua -- Basic class definition ---@class Animal ---@field name string Animal name ---@field species string Species ---@field age number Age local Animal = {} ---@param name string ---@param species string ---@param age number function Animal.new(name, species, age) return setmetatable({ name = name, species = species, age = age }, {__index = Animal}) end function Animal:speak() print(self.name .. " makes a sound") end ``` -------------------------------- ### Multi-Version Compatibility Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/version.md List multiple versions separated by commas to indicate compatibility with any of the specified Lua versions. This example is compatible with Lua 5.1, 5.2, and 5.3. ```lua -- Multi-version compatibility ---@version 5.1,5.2,5.3 function compatibleFeature() -- code compatible with multiple versions end ``` -------------------------------- ### One item per line layout example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_formatter/tutorial_EN.md Shows a chained method call formatted with one item per line when narrower layouts are less clear. ```lua builder :set_name(name) :set_age(age) :build() ``` -------------------------------- ### New Replacement Methods Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md This snippet shows the modern replacement methods for a deprecated class method. ```lua -- New replacement method ---@param path string File path ---@return string File content function FileManager:readFileSync(path) local file = io.open(path, "r") if not file then error("Could not open file: " .. path) end local content = file:read("*a") file:close() return content end ``` -------------------------------- ### Multiple Inheritance Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/class.md Demonstrates multiple inheritance by defining a 'Duck' class that inherits from 'Animal', 'Flyable', and 'Swimmable'. ```lua -- Multiple inheritance example ---@class Flyable ---@field maxAltitude number Maximum flight altitude ---@class Swimmable ---@field maxDepth number Maximum diving depth ---@class Duck : Animal, Flyable, Swimmable ---@field featherColor string Feather color local Duck = {} ``` -------------------------------- ### Index Signature Field Examples Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Illustrates the use of index signatures for defining fields with arbitrary keys and types in 'Configuration' and 'ScoreBoard' classes. ```lua -- Index signature fields ---@class Configuration ---@field host string Host address ---@field port number Port number ---@field [string] any Other configuration items (arbitrary string keys) ---@class ScoreBoard ---@field [string] number Mapping from student names to scores ``` -------------------------------- ### New Replacement Function Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md This snippet shows a modern replacement function that can be referenced in a deprecation notice. ```lua -- New replacement function ---@param numbers number[] Array of numbers ---@return number Sum function newCalculateSum(numbers) return table.reduce(numbers, function(acc, num) return acc + num end, 0) end ``` -------------------------------- ### Lua @nodiscard Usage Examples - Good Practices Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/nodiscard.md Illustrates correct usage patterns in Lua where the return values of @nodiscard functions are properly checked and handled. ```lua -- GOOD: Result is checked local isValid = validateInput(userInput) if not isValid then print("Invalid input") end -- GOOD: Error handling local data, error = parseJSON(jsonString) if error then print("Parse error:", error) return end -- GOOD: File operation result checked local success, writeError = writeFileSecure("output.txt", "data") if not success then print("Write failed:", writeError) end ``` -------------------------------- ### Game Engine Meta Definitions (Love2D) Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/meta.md Example of @meta definitions for a game engine like Love2D, documenting modules like 'love.graphics'. ```APIDOC ---@meta love2d ---@class love local love = {} ---@class love.graphics love.graphics = {} ---@param text string Text to draw ---@param x number X position ---@param y number Y position function love.graphics.print(text, x, y) end ---@param r number Red component (0-1) ---@param g number Green component (0-1) ---@param b number Blue component (0-1) ---@param a? number Alpha component (0-1) function love.graphics.setColor(r, g, b, a) end ---@param mode string Draw mode ---@param ... number Coordinates function love.graphics.polygon(mode, ...) end ``` -------------------------------- ### Reference external documentation with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Link to external URLs or local documentation files using @see. This is crucial for providing access to detailed guides, specifications, or API references. ```lua -- Reference to external documentation ---@param config table Configuration object ---@return HTTPClient Client instance ---@see https://example.com/docs/http-client HTTP Client Documentation ---@see README.md#configuration Configuration Guide function createHTTPClient(config) return HTTPClient.new(config) end ``` -------------------------------- ### Basic Async Function Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/async.md Demonstrates a basic asynchronous function using coroutines to simulate an HTTP request with a delay. The function uses coroutine.wrap and coroutine.yield to manage the asynchronous flow. ```lua ---@async ---@param url string Request URL ---@return string Response content function fetchData(url) -- Simulate async HTTP request return coroutine.wrap(function() print("Starting request:", url) -- Simulate network delay local co = coroutine.running() timer.setTimeout(function() coroutine.resume(co, "Response data: " .. url) end, 1000) return coroutine.yield() end)() end ``` -------------------------------- ### New Replacement Class Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md This snippet defines a modern class that serves as a replacement for a deprecated one. ```lua -- New replacement class ---@class ModernUser ---@field id number ---@field name string ---@field email string ---@field createdAt string local ModernUser = {} ``` -------------------------------- ### Generic Index Signature Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Demonstrates a generic index signature for a 'GenericContainer' class, allowing indexed access with a type parameter 'T'. ```lua -- Index signature fields ---@class GenericContainer ---@field [number] T Array index access ``` -------------------------------- ### Partial Class Definition Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/class.md Shows the 'partial' class modifier, allowing extension of an existing 'Animal' class by adding a 'weight' field. ```lua -- Partial class definition example (extends existing class) ---@class (partial) Animal ---@field weight number Weight ``` -------------------------------- ### Example .emmyrc.json configuration Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_check/README.md Configure diagnostic rules, such as disabling the 'unused' diagnostic, in a JSON configuration file. ```json { "diagnostics": { "disable": [ "unused" ] } } ``` -------------------------------- ### EmmyLua Enhanced Rendering Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/features/features_EN.md Demonstrates EmmyLua's private protocol for rendering enhancements, showing how mutable variables are underlined and constants are displayed normally. ```lua local mutable_var = 10 -- Mutable variable: underlined local const_value = 42 -- Constant: normal display ``` -------------------------------- ### Neovim LSP Configuration for emmylua_ls Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Configure Neovim to use emmylua_ls as its language server. This example assumes Neovim 0.11+ and that emmylua_ls is available in the PATH. ```lua vim.lsp.config("emmylua_ls", { cmd = { "emmylua_ls" }, filetypes = { "lua" }, root_markers = { ".emmyrc.json", ".luarc.json", ".git" }, }) vim.lsp.enable("emmylua_ls") ``` -------------------------------- ### Built-in Function Definitions (_G) Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/meta.md Example of using @meta to document built-in global functions like 'type', 'pcall', and 'coroutine.resume'. ```APIDOC ---@meta _G ---@param obj any Object to get type of ---@return string Type name function type(obj) end ---@param func function Function to call ---@param ... any Arguments ---@return boolean success, ... function pcall(func, ...) end ---@param co thread Coroutine ---@param ... any Values to pass ---@return boolean success, ... function coroutine.resume(co, ...) end ``` -------------------------------- ### Lua Document Link Recognition Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/features/features_EN.md Shows how EmmyLua recognizes and makes file paths in Lua code clickable links. This allows for quick navigation to referenced files. ```lua -- File paths automatically recognized as clickable links local config_path = "./config/settings.lua" local image_file = "./assets/images/logo.png" ``` -------------------------------- ### Lua Version Range Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/version.md Specify a range of compatible Lua versions using '>' and '<' operators. This example is compatible with Lua versions from 5.2 up to (but not including) 5.5. ```lua -- Version range ---@version >5.2,<5.5 function rangeCompatible() -- compatible from 5.2 to 5.4 end ``` -------------------------------- ### Library-Specific Meta File (JSON) Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/meta.md Example of a @meta file for a specific library, 'json'. It defines the 'json' class and its associated functions like 'decode' and 'encode'. ```APIDOC ---@meta json ---@class json local json = {} ---@param str string JSON string ---@return table Parsed object ---@return nil, string Error message on failure function json.decode(str) end ---@param obj table Object to encode ---@param pretty? boolean Pretty print ---@return string JSON string function json.encode(obj, pretty) end return json ``` -------------------------------- ### Configure Diagnostics Severity and Rules Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/config/emmyrc_json_EN.md Example of how to configure diagnostic rules and severity levels in the .emmyrc.json file. Use this to customize error reporting for specific rules. ```json { "diagnostics": { "disable": ["undefined-global"], "severity": { "undefined-global": "warning", "unused": "hint" }, "enables": ["unknown-doc-tag"] } } ``` -------------------------------- ### Reference related configurations with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Use @see to link to configuration files or documentation related to specific settings. This improves discoverability of configuration options. ```lua -- Reference to related configurations ---@class AppConfig ---@field database table Database configuration ---@field server table Server configuration ---@see config/database.lua For database settings ---@see config/server.lua For server settings ---@see docs/configuration.md For configuration guide local AppConfig = {} ``` -------------------------------- ### Configure emmylua_ls for Other Editors (Stdio Mode) Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Example JSON configuration for editors using emmylua_ls via standard input/output. This is the default and recommended mode for most LSP clients. ```json { "command": "emmylua_ls", "args": [] } ``` -------------------------------- ### Format Lua Code with Path-Aware Configuration Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_formatter/README.md Demonstrates how to use `resolve_config_for_path` to get configuration based on a file path, and then use `check_text` with the resolved configuration. This pattern is crucial for applying Lua syntax levels defined in the configuration. ```rust use std::path::Path; use emmylua_formatter::{check_text, resolve_config_for_path}; fn main() -> Result<(), Box> { let source_path = Path::new("workspace/scripts/main.lua"); let source = "---@param value string\nlocal function f(value) end\n"; let resolved = resolve_config_for_path(Some(source_path), None)?; let result = check_text(source, resolved.config.syntax.level.into(), &resolved.config); assert!(resolved.source_path.is_some()); assert!(result.changed); Ok(()) } ``` -------------------------------- ### Lua @nodiscard Usage Examples - Bad Practices (Warnings) Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/nodiscard.md Demonstrates incorrect usage in Lua where return values of @nodiscard functions are discarded, which will trigger IDE warnings. ```lua -- BAD: These will show warnings in IDE validateInput(userInput) -- Warning: Return value should not be discarded parseJSON(jsonString) -- Warning: Must check for errors writeFileSecure("test.txt", "content") -- Warning: Critical: File operation result must be checked ``` -------------------------------- ### EmmyLua Function Overload Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Shows how to define multiple signatures for a single function using the `@overload` annotation. This is useful for functions with varying parameter types or return values. ```lua ---@overload fun(x: number): number ``` -------------------------------- ### Instantiate and Use Generic Class Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/generic.md Demonstrates how to create instances of a generic class with specific type parameters and use their methods. ```lua -- Usage examples local stringStack = Stack.new() -- Stack stringStack:push("hello") stringStack:push("world") local numberStack = Stack.new() -- Stack numberStack:push(1) numberStack:push(2) ``` -------------------------------- ### Lua Custom Folding Region Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/features/features_EN.md Demonstrates how to define custom folding regions in Lua code using '--region' and '--endregion' comments. This is useful for organizing and collapsing specific blocks of code. ```lua --region Custom Folding Region -- Code to be folded here local config = { -- Configuration items... } --endregion ``` -------------------------------- ### EmmyLua Type Alias Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Provides an example of defining a type alias for simplifying complex type expressions. This improves code readability. ```lua ---@alias StringOrNumber string | number ``` -------------------------------- ### Build the formatter binary Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_formatter/tutorial_EN.md Build the formatter executable from the workspace using cargo. ```bash cargo build --release -p emmylua_formatter ``` -------------------------------- ### Reference standards and specifications with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Link to relevant standards, RFCs, or external tools using @see. This provides context and resources for understanding protocols or specifications. ```lua -- Reference to standards and specifications ---@param jwt string JWT token ---@return table Decoded payload ---@see RFC 7519 JSON Web Token specification ---@see https://jwt.io/ JWT debugging tools function decodeJWT(jwt) return jwt.decode(jwt) end ``` -------------------------------- ### Start EmmyLua LS in TCP Mode Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Starts the EmmyLua language server in TCP communication mode. Specify the port, log level, and log path as needed. The default port is 5007. ```bash emmylua_ls -c tcp --port 5007 --log-level debug --log-path ./logs ``` -------------------------------- ### Basic Class Definition Syntax Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/class.md Illustrates the fundamental syntax for defining a class, optionally specifying parent classes for inheritance. ```lua -- Basic class definition ---@class [: [, ...]] ``` ```lua -- Exact class definition (prohibits dynamic field addition) ---@class (exact) [: ...] ``` ```lua -- Partial class definition (allows extending existing classes) ---@class (partial) ``` ```lua ---@class [: ...] ``` -------------------------------- ### Configure Document Formatting with External Tool Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/external_format/external_formatter_options_EN.md Use this configuration to set up an external tool for formatting the entire document. Ensure the specified 'program' is accessible in your system's PATH. ```json { "format" : { "externalTool": { "program": "stylua", "args": [ "-", "--stdin-filepath", "${file}", ], "timeout": 5000 } } } ``` -------------------------------- ### Basic EmmyLua Annotation Syntax Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Demonstrates the fundamental structure for EmmyLua annotations, using the '---@' prefix followed by the annotation name, parameters, and description. ```lua ---@annotation_name parameters description ``` -------------------------------- ### Clone and Build Project Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Clones the EmmyLua Analyzer Rust repository and builds the project. Use specific flags to build only the language server or the entire project. ```bash git clone https://github.com/EmmyLuaLs/emmylua-analyzer-rust.git cd emmylua-analyzer-rust cargo build --release ``` ```bash cargo build --release -p emmylua_ls ``` -------------------------------- ### Generate Documentation Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/README.md Generates documentation for Lua code in the specified source directory and outputs it to the specified output directory. ```bash emmylua_doc_cli ./src --output ./docs ``` -------------------------------- ### GitHub Actions workflow for EmmyLua Check Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_check/README.md Automate code checks in a GitHub Actions workflow by installing and running emmylua_check. ```yaml name: EmmyLua Check on: [push, pull_request] jobs: check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - name: Install emmylua_check run: cargo install emmylua_check - name: Run check run: emmylua_check . ``` -------------------------------- ### Exact Class Definition Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/class.md Illustrates the 'exact' class modifier, which prevents dynamic addition of fields to the 'Point' class. ```lua -- Exact class definition example (cannot add fields dynamically) ---@class (exact) Point ---@field x number ---@field y number local Point = {} ``` -------------------------------- ### Configuration Module with Default and Create Functions Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/module.md Declares a 'config' module with a default configuration and a function to create a merged configuration. Useful for application settings. ```lua ---@module config ---@class AppConfig ---@field debug boolean Debug mode ---@field port number Server port ---@field database {host: string, name: string} ---@field features string[] Enabled features ---@type AppConfig local defaultConfig = { debug = false, port = 8080, database = { host = "localhost", name = "myapp" }, features = {"auth", "logging"} } ---@param userConfig? Partial User configuration ---@return AppConfig Merged configuration local function createConfig(userConfig) local config = {} for k, v in pairs(defaultConfig) do config[k] = v end if userConfig then for k, v in pairs(userConfig) do config[k] = v end end return config end return { default = defaultConfig, create = createConfig } ``` -------------------------------- ### Workspace Library and Package Configuration Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/config/emmyrc_json_EN.md Configure library paths and package directories. Libraries can be simple string paths or objects specifying additional ignore rules for subdirectories or glob patterns. ```json { "workspace": { "library": [ "./types", { "path": "./vendor", "ignoreDir": ["test"], "ignoreGlobs": ["**/*.spec.lua"] } ] } } ``` -------------------------------- ### Deprecated Class Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md Mark an entire class as deprecated, suggesting a newer class for use. This is helpful when refactoring class structures. ```lua -- Deprecated class ---@deprecated Please use ModernUser class instead ---@class OldUser ---@field id number ---@field name string local OldUser = {} ``` -------------------------------- ### Typical CLI Usage for luafmt Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_formatter/README.md Demonstrates common command-line interface operations for the luafmt tool, including writing to files, checking for differences, and processing stdin. ```powershell luafmt src --write ``` ```powershell luafmt . --check --exclude "vendor/**" ``` ```powershell Get-Content script.lua | luafmt --stdin ``` ```powershell Get-Content script.lua | luafmt --stdin --output formatted.lua ``` -------------------------------- ### Reference algorithms with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Link to specific algorithms using @see, especially when providing an implementation of a general algorithm. This helps users choose the most suitable algorithm for their needs. ```lua -- Reference to algorithms ---@param array table Array to sort ---@return table Sorted array ---@see quickSort For large datasets ---@see mergeSort For stable sorting ---@see insertionSort For small datasets function bubbleSort(array) -- Implementation return array end ``` -------------------------------- ### Minimum Lua Version Requirement Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/version.md Use the '>' operator to specify the minimum Lua version required. This example requires Lua 5.2 or later. ```lua -- Minimum version requirement ---@version >5.1 function modernFeature() -- requires features from Lua 5.2+ local function closure() -- uses 5.2+ features end end ``` -------------------------------- ### Lua Basic @nodiscard Function Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/nodiscard.md Demonstrates a simple Lua function marked with @nodiscard, indicating its boolean return value should not be ignored. ```lua -- Basic nodiscard function ---@nodiscard ---@return boolean success function validateInput(input) return input ~= nil and input ~= "" end ``` -------------------------------- ### Reference design patterns with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Use @see to associate code with relevant design patterns. This aids in understanding the architectural choices and common solutions applied. ```lua -- Reference to design patterns ---@class Factory ---@see Builder For complex object construction ---@see Singleton For single instance management ---@see Observer For event notification patterns local Factory = {} ``` -------------------------------- ### Optional Field Definitions Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/field.md Demonstrates how to define optional fields using the '?' marker for a 'UserProfile' class. ```lua -- Optional fields (using ? marker) ---@class UserProfile ---@field avatar? string Avatar URL (optional) ---@field bio? string Personal bio (optional) ---@field phone? string Phone number (optional) ``` -------------------------------- ### EmmyLua Class Definition Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Illustrates how to define a class with fields using EmmyLua annotations. This is useful for structuring complex data objects. ```lua -- Class definition combination ---@class User ---@field id number User ID ---@field name string Username ---@field email string Email address ``` -------------------------------- ### Deprecated Field Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md Use the @deprecated tag on a field within a class or table definition to indicate it should no longer be used, suggesting an alternative field. ```lua -- Deprecated field ---@class APIResponse ---@field success boolean ---@field data any ---@field message string ---@deprecated Please use errorMessage field instead ---@field error string ``` -------------------------------- ### Reference test cases with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Link to test files or specifications using @see. This provides easy access to test cases and behavior definitions. ```lua -- Reference to test cases ---@param input string Input to validate ---@return boolean Is valid ---@see tests/validation_test.lua For test cases ---@see spec/validation.spec For behavior specification function validateInput(input) return input ~= nil and #input > 0 end ``` -------------------------------- ### EmmyLua Generic Function Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Demonstrates the use of generic types in function annotations. This allows for writing flexible functions that can operate on various types. ```lua -- Generic function combination ---@generic T ---@param items T[] List of items ---@param predicate fun(item: T): boolean Filter condition ---@return T[] Filtered list function filter(items, predicate) -- Implementation code end ``` -------------------------------- ### Layout Configuration Defaults Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_formatter/options_EN.md Sets default layout preferences including maximum line width, maximum consecutive blank lines, and expansion behavior for tables and function arguments. Also includes preferences for maintaining source layout and breaking chains. ```toml [layout] max_line_width = 120 max_blank_lines = 1 table_expand = "Auto" call_args_expand = "Auto" func_params_expand = "Auto" prefer_call_args_layout_from_source = false prefer_table_layout_from_source = false prefer_chain_break_on_statement_tail = false ``` -------------------------------- ### Reference error handling with @see Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/see.md Link to error handling utilities, logging mechanisms, or retry strategies using @see. This helps users understand how errors are managed. ```lua -- Reference to error handling ---@param operation function Operation to execute ---@return any result ---@return string? error ---@see ErrorHandler For error processing ---@see Logger For error logging ---@see RetryPolicy For retry strategies function safeExecute(operation) local success, result = pcall(operation) if success then return result, nil else ErrorHandler.process(result) return nil, result end end ``` -------------------------------- ### Specific Lua Version Requirement Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/version.md Use a specific version number to indicate that the code requires that exact Lua version. This example requires Lua 5.4. ```lua -- Specific version ---@version 5.4 function lua54Feature() -- features only available in Lua 5.4 local x = 10 -- constant variable end ``` -------------------------------- ### Constructor Overloads for Vector Class Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/overload.md Illustrates constructor overloading for a 'Vector' class. Multiple 'new' function signatures are defined to allow creating Vector objects with zero, one, two, or three numeric arguments, defaulting to 0 if not provided. ```lua ---@class Vector ---@field x number ---@field y number ---@field z number local Vector = {} ---@overload fun(): Vector ---@overload fun(x: number): Vector ---@overload fun(x: number, y: number): Vector ---@overload fun(x: number, y: number, z: number): Vector ---@param x? number ---@param y? number ---@param z? number ---@return Vector function Vector.new(x, y, z) return setmetatable({ x = x or 0, y = y or 0, z = z or 0 }, {__index = Vector}) end ``` -------------------------------- ### Deprecated Method Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md Mark a method within a class as deprecated, providing guidance on which new methods to use instead. This is common when refactoring class interfaces. ```lua -- Deprecated method ---@class FileManager local FileManager = {} ---@deprecated Use readFileSync or readFileAsync instead ---@param path string File path ---@return string File content function FileManager:loadFile(path) local file = io.open(path, "r") if file then local content = file:read("*a") file:close() return content end return "" end ``` -------------------------------- ### Recommended EmmyLua Formatter Configuration Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_formatter/options_EN.md A minimal configuration for the EmmyLua Formatter, focusing on common layout and comment alignment preferences. ```toml [layout] max_line_width = 100 table_expand = "Auto" call_args_expand = "Auto" func_params_expand = "Auto" [comments] align_in_statements = false align_in_table_fields = true align_in_call_args = true align_in_params = true [align] continuous_assign_statement = false table_field = true ``` -------------------------------- ### EmmyLua Type Casting Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Demonstrates how to perform type casting at runtime using the `@cast` annotation. This is useful when the type system cannot infer the correct type. ```lua ---@cast value string ``` -------------------------------- ### EmmyLua Deprecation Marker Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Illustrates how to mark a function or variable as deprecated using the `@deprecated` annotation. This warns users to avoid using obsolete code. ```lua ---@deprecated Use new method instead ``` -------------------------------- ### EmmyLua Function Definition Example Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/README.md Shows how to annotate function parameters and return values for better type checking and documentation. This helps in understanding function contracts. ```lua -- Function definition combination ---@param name string Username ---@param age number User age ---@return User User object function createUser(name, age) return {id = generateId(), name = name, age = age} end ``` -------------------------------- ### EmmyLua Check CLI Usage Help Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/crates/emmylua_check/README.md Display help information for the emmylua_check command-line tool, including available options and arguments. ```text Usage: emmylua_check [OPTIONS] [WORKSPACE]... Arguments: [WORKSPACE]... Path(s) to workspace directory Options: -c, --config Path to configuration file. If not provided, ".emmyrc.json" and ".luarc.json" will be searched in the workspace directory -i, --ignore Comma-separated list of ignore patterns. Patterns must follow glob syntax -f, --output-format Specify output format [default: text] [possible values: json, text] --output Specify output target (stdout or file path, only used when output_format is json) [default: stdout] --warnings-as-errors Treat warnings as errors --verbose Verbose output -h, --help Print help information -V, --version Print version information ``` -------------------------------- ### Database Module with Connection and Query Functions Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/module.md Declares a 'database' module with types for 'Connection' and 'Database'. Use this to define database interaction interfaces. ```lua ---@module database ---@class Connection local Connection = {} ---@param query string SQL query ---@param params? table Query parameters ---@return table[] Results function Connection:execute(query, params) end ---@return boolean Success function Connection:close() end ---@class Database local Database = {} ---@param config {host: string, port: number, database: string, user: string, password: string} ---@return Connection function Database.connect(config) end ---@param query string SQL query ---@return table[] Results function Database.query(query) end return Database ``` -------------------------------- ### Deprecation with Alternative Explanation Source: https://github.com/emmyluals/emmylua-analyzer-rust/blob/main/docs/emmylua_doc/annotations_EN/deprecated.md Provide a string explanation after the @deprecated tag to guide users to alternative solutions. This is useful for explaining why a function is deprecated and what to use instead. ```lua -- Deprecation with alternative explanation ---@deprecated Please use newCalculateSum function instead ---@param numbers number[] Array of numbers ---@return number Sum function calculateSum(numbers) local sum = 0 for _, num in ipairs(numbers) do sum = sum + num end return sum end ```