### Lua Module Export Example Source: https://roblox.github.io/lua-style-guide/index Demonstrates exporting a module with constants, members, and functions in Lua. Follows PascalCase for module and member names, and LOUD_SNAKE_CASE for constants. ```lua local FOO_THRESHOLD = 6 local FooThing = {} FooThing.someMemberConstant = 5 function FooThing.go() print("Foo Delta:", FooThing.someMemberConstant - FOO_THRESHOLD) end return FooThing ``` -------------------------------- ### Lua Callback Function Example Source: https://roblox.github.io/lua-style-guide/index An example of a Lua function that accepts a callback. This pattern is often used in asynchronous operations, though the example itself is synchronous. ```lua local value = 0 local function doSomething(callback) local newValue = value + 1 callback(newValue) value = newValue end ``` -------------------------------- ### Lua Comment Best Practices: Why vs. What Source: https://roblox.github.io/lua-style-guide/index Provides examples of good and bad Lua comments, emphasizing that comments should explain the reasoning ('why') behind the code, not just what the code does ('what'). ```lua -- Without this condition, the aircraft hangar would fill up with water. if waterLevelTooHigh() then drainHangar() end ``` ```lua -- Check if the water level is too high. if waterLevelTooHigh() then -- Drain the hangar drainHangar() end ``` -------------------------------- ### Lua Multiple Return Values Example Source: https://roblox.github.io/lua-style-guide/gotchas Demonstrates how Lua functions can return multiple values and the behavior when these values are used in different contexts, including potential data loss. ```lua local function values(n) if n == 1 then return 1 elseif n == 2 then return 1, 2 else return 1, 2, 3 end end print(values(2)) -- 1 2 print(values(1), values(2)) -- 1 1 2 print(values(3), values(2)) -- 1 1 2 (!) print(values(3), values(2), 1) -- 1 1 1 (!) ``` -------------------------------- ### Lua Formatting: Spaces Around Operators Source: https://roblox.github.io/lua-style-guide/index Illustrates the correct usage of spaces around operators in Lua for readability, with an example showing proper spacing for arithmetic operations. ```lua print(5 + 5 * 6^2) ``` -------------------------------- ### Require Library API (Lua) Source: https://roblox.github.io/lua-style-guide/index Shows how consumers of a library should require the API definition and then access public modules. ```Lua local ReplicatedStorage = game:GetService("ReplicatedStorage") local MyLibrary = require(ReplicatedStorage.MyLibrary) local MyModule = MyLibrary.MyModule ``` -------------------------------- ### Lua Function Declaration: Prefix Syntax Source: https://roblox.github.io/lua-style-guide/index Shows the preferred method for declaring named functions in Lua using the function-prefix syntax, emphasizing local declarations for non-member functions and providing examples of good and bad practices. ```lua local function add(a, b) return a + b end ``` ```lua -- This is a global! function add(a, b) return a + b end local add = function(a, b) return a + b end ``` ```lua -- An exception can be made for late-initializing functions in conditionals: local doSomething if CONDITION then function doSomething() -- Version of doSomething with CONDITION enabled end else function doSomething() -- Version of doSomething with CONDITION disabled end end ``` -------------------------------- ### Lua if-then-else Expression within Table Definitions Source: https://roblox.github.io/lua-style-guide/index Provides an example of using `if-then-else` expressions within table definitions or function calls, demonstrating how to handle cases where converting to a standard `if` statement would be cumbersome. ```lua local thing = makeSomething("Foo", { OneChild = if someFlag() then makeSomething("Bar", { scale = 1, }) else makeSomething("Bar", { scale = 2, }), TwoChild = makeSomething("Baz"), }) ``` ```lua local thing = makeSomething("Foo", { OneChild = if someFlag() then makeSomething("Bar", { scale = 1, }) else makeSomething("Bar", { scale = 2, }), TwoChild = makeSomething("Baz"), }) ``` ```lua local thing = makeSomething("Foo", { OneChild = if someFlag() then makeSomething("Bar", { scale = 1, }) else makeSomething("Bar", { scale = 2, }), TwoChild = makeSomething("Baz"), }) ``` -------------------------------- ### Lua Formatting: Avoid Braces on New Lines Source: https://roblox.github.io/lua-style-guide/index Highlights the Lua style guide's recommendation against placing curly braces for tables on their own lines, as it can disrupt readability. It provides examples of correct and incorrect brace placement. ```lua local foo = { bar = { baz = "baz", }, } frob({ x = 1, }) ``` -------------------------------- ### Require Library Internals (Lua) Source: https://roblox.github.io/lua-style-guide/index Demonstrates how internal modules of a library should require their public and private modules using the 'require' function. ```Lua -- in MyLibrary/Foo.lua local MyLibrary = script.Parent local MyModule = require(MyLibrary.MyModule) ``` -------------------------------- ### Lua if-then-else with elseif Clauses Source: https://roblox.github.io/lua-style-guide/index Shows the correct formatting for `if-then-else` expressions that include `elseif` clauses, placing the `elseif (condition) then` on a new line. ```lua local scale = if someFlag() then 1 elseif someOtherFlag() then 0.5 else 2 ``` ```lua local thing = makeSomething("Foo", { OneChild = if someFlag() then makeSomething("Bar", { scale = 1, }) elseif someOtherFlag() then makeSomething("Bar", { scale = 0.5, }) else makeSomething("Bar", { scale = 2, }), TwoChild = makeSomething("Baz"), }) ``` -------------------------------- ### Lua Single-Line Comments Source: https://roblox.github.io/lua-style-guide/index Demonstrates the use of single-line comments in Lua for inline notes and multi-line explanations. It highlights the importance of wrapping comments to 80 columns for readability. ```lua -- This condition is really important because the world would blow up if it -- were missing. if not foo then stopWorldFromBlowingUp() end ``` -------------------------------- ### Lua Block Comments for Documentation Source: https://roblox.github.io/lua-style-guide/index Illustrates how to use Lua block comments (`--[[ ... ]]`) for documenting files, functions, or objects. This method is recommended for providing detailed explanations of purpose and intent. ```lua --[[ Shuts off the cosmic moon ray immediately. Should only be called within 15 minutes of midnight Mountain Standard Time, or the cosmic moon ray may be damaged. ]] local function stopCosmicMoonRay() end ``` -------------------------------- ### Lua Class Instance Creation and Method Invocation Source: https://roblox.github.io/lua-style-guide/index Demonstrates how to create an instance of a Lua class using its constructor and invoke its methods. It shows accessing properties and calling methods that are resolved via the metatable's `__index`. ```lua local instance = MyClass.new(0) -- Properties on the instance are visible, since it's just a table: print(tostring(instance.property)) -- "0" -- Methods are pulled from MyClass because of our metatable: instance:addOne() print(tostring(instance.property)) -- "1" ``` -------------------------------- ### Lua Class Definition: Empty Table Initialization Source: https://roblox.github.io/lua-style-guide/index Initializes an empty table for a class definition in Lua. This serves as the base for further class properties and methods. ```lua local MyClass = {} ``` -------------------------------- ### Lua Class Constructor with Metatable Source: https://roblox.github.io/lua-style-guide/index Defines a constructor function (`new`) for a Lua class. It initializes an instance table, sets the metatable with `__index` pointing to the class, and returns the instance. Includes type annotations for Luau compatibility. ```lua -- The default constructor for our class is called `new` by convention. function MyClass.new(property: number): ClassType local self = { -- Define members of the instance here, even if they're `nil` by default. property = property, } -- Tell Lua to fall back to looking in MyClass.__index for missing fields. setmetatable(self, MyClass) return self end ``` -------------------------------- ### Lua Formatting: Spaces After Commas Source: https://roblox.github.io/lua-style-guide/index Demonstrates the Lua convention of placing a space after each comma in table definitions and function calls to enhance readability. ```lua local friends = {"bob", "amy", "joe"} foo(5, 6, 7) ``` -------------------------------- ### Lua Function Calls: Parentheses Source: https://roblox.github.io/lua-style-guide/index Highlights the importance of using parentheses when calling Lua functions for better code parsing and readability, contrasting it with omitting parentheses. ```lua local x = doSomething("home") local y = doSomethingElse({u = 1, v = 2}) ``` ```lua local x = doSomething "home" local y = doSomethingElse{u = 1, v = 2} ``` -------------------------------- ### Lua if-then-else Expression for Value Selection Source: https://roblox.github.io/lua-style-guide/index Demonstrates the preferred use of `if-then-else` expressions for selecting a value based on a condition, improving readability and safety compared to the `and`/`or` pattern. ```lua local scale = if someFlag() then 1 else 2 ``` ```lua local scale = someFlag() and 1 or 2 ``` -------------------------------- ### Lua Multi-line if-then-else Expression Formatting Source: https://roblox.github.io/lua-style-guide/index Illustrates the correct formatting for multi-line `if-then-else` expressions in Lua, ensuring `then` and `else` are on new lines and indented once for better readability. ```lua local scale = if someReallyLongFlagName() or someOtherReallyLongFlagName() then 1 else 2 ``` ```lua local scale = if someReallyLongFlagName() or someOtherReallyLongFlagName() then 1 else 2 ``` ```lua local scale = if someReallyLongFlagName() or someOtherReallyLongFlagName() then 1 else 2 ``` ```lua local scale = if someReallyLongFlagName() or someOtherReallyLongFlagName() then 1 else 2 ``` -------------------------------- ### Lua Import Block Structure Source: https://roblox.github.io/lua-style-guide/index Demonstrates the recommended structure for import blocks in Lua projects, including relative paths for common ancestors, requiring packages, and importing modules from the same project. This helps in organizing dependencies and improving code readability. ```lua -- 1. A definition of a common ancestor. -- Use a relative path to make sure your project works in multiple locations! local MyProject = script.Parent -- 2. A block of all imported packages. -- Baz is a library we depend on in our project, so we require its API directly... local Baz = require(MyProject.Packages.Baz) -- 3. A block for definitions derived from packages. -- ...and then access its members through that API. These are simple so we don't need to break them down. local Bazifyer = Baz.Bazifyer local UnBazifyer = Baz.UnBazifyer -- 4. A block for modules imported from the same project. -- Defining the path to FooBar separately makes it faster to write and for others to read! local FooBar = MyProject.FooBar local Foo = require(FooBar.Foo) local Bar = require(Foobar.Bar) ``` -------------------------------- ### Lua Class Definition: Metatable __index Setup Source: https://roblox.github.io/lua-style-guide/index Sets the `__index` metatable property for a Lua class back to itself. This is a common pattern to enable prototype-based inheritance, allowing instances to fall back to the class table for missing properties. ```lua MyClass.__index = MyClass ``` -------------------------------- ### Lua Formatting: One Statement Per Line Source: https://roblox.github.io/lua-style-guide/index Shows the best practice in Lua for placing function bodies and statements on new lines for improved clarity, especially for functions returning multiple values or simple conditional returns. ```lua table.sort(stuff, function(a, b) local sum = a + b return math.abs(sum) > 2 end) ``` ```lua Rodux.Store.new(function(state) return state end, mockState, nil) Rodux.Store.new(function(state) return state, mockState end, nil) ``` ```lua if valueIsInvalid then return end ``` -------------------------------- ### Lua Formatting: Inline Block Syntax Elements Source: https://roblox.github.io/lua-style-guide/index Shows the preferred Lua style of keeping opening syntax elements (like curly braces for tables or `then` for `if`) inline with their statements for better code flow. ```lua local foo = { bar = 2, } if foo then -- do something end ``` -------------------------------- ### Lua: Array Length Operator (#) Behavior Source: https://roblox.github.io/lua-style-guide/gotchas Illustrates how the Lua length operator (#) and the 'ipairs' iterator function work with numerical indices. It shows that only contiguous numerical indices starting from 1 are counted, excluding other keys or non-contiguous elements. ```Lua local a = { 0 = "not counted", 1 = "counted", 2 = "counted", 3 = "counted", 5 = "not counted", X = "not counted", } local n = #a -- 3 for k, v in ipairs(a) do print(k, v) -- Prints the three "counted" values end ``` -------------------------------- ### Guarding Against Typos with __index Metamethod Source: https://roblox.github.io/lua-style-guide/index This snippet demonstrates how to use the `__index` metamethod in Lua to guard against typos when accessing enum-like tables. It throws an error for invalid keys, helping to catch bugs early. ```lua local MyEnum = { A = "A", B = "B", C = "C", } setmetatable(MyEnum, { __index = function(self, key) error(string.format("%q is not a valid member of MyEnum", tostring(key)), 2) end, }) ``` -------------------------------- ### Lua Control Flow Blocks without Parentheses Source: https://roblox.github.io/lua-style-guide/index Illustrates the Lua convention of omitting parentheses around conditions in `if`, `while`, and `repeat` blocks, as they are not required and can clutter the code. ```lua if CONDITION then end ``` ```lua while CONDITION do end ``` ```lua repeat until CONDITION ``` -------------------------------- ### Lua: Formatting Tables and Arrays Source: https://roblox.github.io/lua-style-guide/index Demonstrates how to format tables and arrays in Lua, including dictionary-like and list-like structures. It covers breaking tables with multiple keys or nested sub-tables onto multiple lines and adding trailing commas for easier modifications. ```lua local foo = { type = "foo" } local bar = { type = "bar", phrase = "hooray", } -- It's also okay to use multiple lines for a single field local baz = { type = "baz", } local stuff = { hello = "world", hola = "mundo", howdy = "y'all", sup = "homies" } local libs = { "roact", "rodux", "testez", "cryo", "otter" } -- You can break these onto multiple lines, which makes diffs cleaner: local libs = { "roact", "rodux", "testez", "cryo", "otter", } -- We can also group them, if grouping has useful information: local libs = { "roact", "rodux", "cryo", "testez", "otter", } ``` -------------------------------- ### Lua Whitespace: Single Empty Line for Grouping Source: https://roblox.github.io/lua-style-guide/index Demonstrates the recommended use of a single empty line to group related code blocks in Lua, improving readability without excessive whitespace. ```lua local Foo = require(Common.Foo) local function gargle() -- gargle gargle end Foo.frobulate() Foo.frobulate() Foo.munge() ``` -------------------------------- ### Lua do Blocks for Variable Scope Management Source: https://roblox.github.io/lua-style-guide/index Demonstrates the use of `do` blocks in Lua to limit the scope of variables, ensuring they are only accessible within the block and preventing potential naming conflicts. ```lua local getId do local lastId = 0 getId = function() lastId = lastId + 1 return lastId end end ``` -------------------------------- ### Lua if-then-else Expression Conversion to Standard if Statement Source: https://roblox.github.io/lua-style-guide/index Shows how to convert a complex `if-then-else` expression that spans multiple lines into a standard `if` statement for improved clarity when it becomes too lengthy. ```lua local scale if someReallyLongFlagName() or someOtherReallyLongFlagName() then scale = Vector2.new(1, 1) + someVectorOffset + someOtherVector else scale = Vector2.new(1, 1) + someNewVectorOffset + someNewOtherVector end ``` ```lua local scale = if someReallyLongFlagName() or someOtherReallyLongFlagName() then Vector2.new(1, 1) + someVectorOffset + someOtherVector else Vector2.new(1, 1) + someNewVectorOffset + someNewOtherVector ``` -------------------------------- ### Lua: Ternary Operator Imitation with 'and'/'or' Source: https://roblox.github.io/lua-style-guide/gotchas Demonstrates the common Lua pattern of using 'and' and 'or' to mimic a ternary operator. It highlights how short-circuiting and truthy/falsy evaluations can lead to unexpected results when the middle operand is falsy. ```Lua local a = {u="v"} local b = 1 local c = false local d = a or b -- d equals a local e = c and a or b -- e equals b ``` ```Lua local a = getX() local b = getY() local c = true local d = c and a or b ``` -------------------------------- ### Lua: Formatting Nested Tables and Function Arguments Source: https://roblox.github.io/lua-style-guide/index Illustrates formatting for deeply nested tables and long argument lists in Lua. It shows how to expand subtables onto new lines for cleaner diffs and discusses acceptable variations for table literals, especially in contexts like Roact. ```lua local aTable = { { aLongKey = aLongValue, anotherLongKey = anotherLongValue, }, { aLongKey = anotherLongValue, anotherLongKey = aLongValue, }, } doSomething( { aLongKey = aLongValue, anotherLongKey = anotherLongValue, }, { aLongKey = anotherLongValue, anotherLongKey = aLongValue, } ) local aTable = {{ aLongKey = aLongValue, anotherLongKey = anotherLongValue, }, { aLongKey = anotherLongValue, anotherLongKey = aLongValue, }} doSomething({ aLongKey = aLongValue, anotherLongKey = anotherLongValue, }, { aLongKey = anotherLongValue, anotherLongKey = aLongValue, }) doSomething({ aLongKey = aLongValue, anotherLongKey = anotherLongValue }, notATableLiteral, { aLongKey = anotherLongValue, anotherLongKey = aLongValue }) doSomething( { aLongKey = aLongValue, anotherLongKey = anotherLongValue }, notATableLiteral, { aLongKey = anotherLongValue, anotherLongKey = aLongValue } ) ``` -------------------------------- ### Lua: 1-Based Indexing Reminder Source: https://roblox.github.io/lua-style-guide/gotchas Reminds developers that Lua arrays and indices are 1-based, not 0-based. This is crucial for mathematical operations on indices, such as modulo operations for wrapping. -------------------------------- ### Lua Block Comments for Section Documentation Source: https://roblox.github.io/lua-style-guide/index Shows an advanced use of Lua block comments to document logical sections of code, such as a group of related functions. This approach aims to improve readability without using traditional section comments. ```lua --[[ All of the readX functions return the next token from the string passed in to the Reader or returns nil if the next token doesn't match the type the function is trying to read. local test = "123 ABC" i = reader:readInt() print(i, ",", test.remaining) -- 123 , ABC readInt reads an integer, positive or negative. ]] function Reader:readInt() -- ... -- readFloat reads a floating point number, but does not accept -- scientific notation function Reader:readFloat() -- ... ``` -------------------------------- ### Lua Default Value Handling with Multiple Returns Source: https://roblox.github.io/lua-style-guide/gotchas Illustrates a scenario where a function using default values might unintentionally be affected by a second return value from another function call. ```lua local function position(x, y, z) z = z or 0 -- default z to 0 -- ... end position(getX(), getY()) ``` -------------------------------- ### Lua Table Declaration with Trailing Commas Source: https://roblox.github.io/lua-style-guide/index Illustrates the practice of adding trailing commas in multi-line Lua tables to facilitate easier sorting and cleaner diffs when adding new items. ```lua local frobs = { andrew = true, billy = true, caroline = true, } ``` -------------------------------- ### Lua: Returning Nothing vs. Returning Nil Source: https://roblox.github.io/lua-style-guide/gotchas Highlights the subtle difference between a function explicitly returning 'nil' and a function implicitly returning nothing (by not having a return statement). This distinction affects how values are handled, particularly with functions like 'table.insert'. ```Lua local function zero() return end local function one() return nil end local a = {1} table.insert(a, one()) -- Inserting nil leaves a unchanged table.insert(a, zero()) -- Error! wrong number of arguments to 'insert' ``` -------------------------------- ### Lua Formatting Exception: Complex Inline Tables/Functions Source: https://roblox.github.io/lua-style-guide/index Presents an exception to the rule of keeping braces inline, showing how to format large inline tables or functions across multiple lines for improved clarity in function calls. ```lua -- In function calls with large inline tables or functions, sometimes it's -- more clear to put braces and functions on new lines: foo( { type = "foo", }, function(something) print("Hello," something) end ) -- As opposed to: foo({ type = "foo", }, function(something) -- How do we indent this line? print("Hello,", something) end) ``` -------------------------------- ### Lua Helper Variable for Long Conditions in if-then-else Source: https://roblox.github.io/lua-style-guide/index Demonstrates using a helper variable to store the result of a long or complex condition in an `if-then-else` expression, making the code cleaner and easier to read. ```lua local useNewScale = someReallyReallyLongFunctionName() and someOtherReallyLongFunctionName() local scale = if useNewScale then 1 else 2 ``` ```lua local scale = if someReallyReallyLongFunctionName() and someOtherReallyLongFunctionName() then 1 else 2 ``` -------------------------------- ### Lua: Safer 'if' Expressions Source: https://roblox.github.io/lua-style-guide/gotchas Presents the modern Lua 'if' expression as a safer and more readable alternative to the 'and'/'or' ternary imitation. This syntax avoids issues when intermediate values might be falsy. ```Lua local a = getX() local b = getY() local c = true local d = if c then a else b -- No problem if a is falsy. ``` -------------------------------- ### Lua String Literals: Double Quotes Source: https://roblox.github.io/lua-style-guide/index Demonstrates the preferred use of double quotes for string literals in Lua to avoid escaping apostrophes and improve readability. Includes an exception for strings containing double quotes. ```lua print("Here's a message!") ``` ```lua print('Quoth the raven, "Nevermore"') ``` -------------------------------- ### Lua Table Functions: Dot and Colon Syntax Source: https://roblox.github.io/lua-style-guide/index Explains the correct usage of the dot (.) and colon (:) syntax when declaring functions within Lua tables to denote the intended calling convention, differentiating between member and non-member functions. ```lua -- This function should be called as Frobulator.new() function Frobulator.new() return {} end -- This function should be called as Frobulator:frob() function Frobulator:frob() print("Frobbing", self) end ``` ```lua function Frobulator.garb(self) print("Frobbing", self) end Frobulator.jarp = function() return {} end ``` -------------------------------- ### Lua: Formatting Long Expressions and Conditions Source: https://roblox.github.io/lua-style-guide/index Provides guidelines for breaking down long expressions and conditions in Lua. It recommends placing operators at the beginning of new lines for clarity and indenting subexpressions. For 'if' statements, it suggests separating the condition from the 'then' block. ```lua if someReallyLongCondition and someOtherReallyLongCondition and somethingElse then doSomething() doSomethingElse() end ``` -------------------------------- ### Lua Function with Error Handling Source: https://roblox.github.io/lua-style-guide/index Illustrates a Lua function that returns success/failure status and a result or error object. It includes an assertion for input validation and demonstrates returning a boolean success flag and either a success message or an error object. ```lua local function thisCanFail(someValue) assert(typeof(someValue) == "string", "someValue must be a string!") if success() then return true, "Congratulations! You won!" else return false, Error.new("ERR_BLAH", "Something horrible failed!") end end ``` -------------------------------- ### Lua Whitespace: No Vertical Alignment Source: https://roblox.github.io/lua-style-guide/index Illustrates the importance of avoiding vertical alignment in Lua code for better editability and consistency. It shows the preferred method of aligning variables without strict vertical alignment. ```lua local frobulator = 132 local grog = 17 ``` -------------------------------- ### Lua Class Type Checking Function Source: https://roblox.github.io/lua-style-guide/index Provides a function to check if a given Lua instance belongs to a specific class by inspecting its metatable's `__index` property. This is useful for runtime type verification. ```lua function MyClass.isMyClass(instance) return getmetatable(instance).__index == MyClass end ``` -------------------------------- ### Luau Class Type Definition Source: https://roblox.github.io/lua-style-guide/index Defines the type signature for a Luau class, specifying its members and their types. This aids in static analysis and type checking, ensuring consistency between the type definition and the actual class implementation. ```lua -- Export the type if you'd like to use it outside this module export type ClassType = typeof(setmetatable( {} :: { property: number, }, MyClass )) ``` -------------------------------- ### Lua: Handling Sparse Arrays and Nil Values Source: https://roblox.github.io/lua-style-guide/gotchas Explains the impact of nil values and sparse numerical indices on Lua's length operator (#) and 'ipairs'. It suggests using a '.n' field to manually track the length of sparse arrays, similar to 'table.pack'. ```Lua local a = {1, 2, 3, 4, 5} a[4] = getSomething() -- happens to return nil local n = #a -- 3 ``` -------------------------------- ### Lua Class Method Definition with Type Annotation Source: https://roblox.github.io/lua-style-guide/index Defines a method for a Lua class using dot notation for explicit `self` type annotation. This practice helps Luau's type checker understand the `self` parameter, improving type inference and static analysis. ```lua function MyClass.addOne(self: ClassType) self.property += 1 end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.