The Length Operator '#'
Part of the Fundamentals section of Coddy's Lua journey. Lesson 60 of 90.
You'll often need to know how many elements a list holds. Lua provides a simple and convenient way to do this using the length operator #.
The length operator is placed directly in front of a table variable and returns the number of elements in a list-style table, one whose values sit at positions 1, 2, 3 and so on:
local players = {"Alice", "Bob", "Charlie"}
print(#players) -- outputs: 3The result is the position of the last element, counting up from index 1. If a list has a gap (a nil between two values), the result is not reliable, and keys that are not numbers, such as name = "Ana", are never counted. It's particularly useful when you need to know the size of a list for loops, conditions, or to display information to users.
local scores = {100, 85, 92, 78, 95}
local totalPlayers = #scores
print("Number of players:", totalPlayers) -- outputs: Number of players: 5Challenge
EasyCreate a guild roster management system that tracks the number of active members. First, create a table named guildMembers containing exactly five string values: "Warrior", "Mage", "Archer", "Healer", and "Rogue". After creating the table, use the length operator # to determine how many members are in the guild and print this count.
Try it yourself
-- TODO: Create the guildMembers table with the specified values
-- TODO: Use the length operator to count the members
-- TODO: Print the countThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators 2 Relational & Logic
Equality OperatorsRelational OperatorsThe 'and' OperatorThe 'or' OperatorThe 'not' OperatorShort-Circuit EvaluationTruthy and Falsy ValuesRecap - Simple Logic7Basic Conditional Logic
The if-then StatementThe if-then-else StatementThe elseif StatementRecap - Treasure Chest10Tables Part 1: List-Style
What is a Table?Creating a TableAccessing Elements by IndexModifying Elements by IndexThe Length Operator '#'table.insert()table.remove()Recap - Manage Party Members2Variables and Data Types
What is a Variable?NumbersStringsBooleansThe Value 'nil'The type() FunctionNaming ConventionsRecap - Character Profile5Basic Output
Printing LiteralsPrinting VariablesPrinting Multiple ValuesCombining Strings & VariablesThe tostring() FunctionInputCastRecap - Status ReportRecap - Till 1208String Manipulation Basics
string.len()string.upper & string.lowerstring.sub()string.rep()string.find()Recap - Format Username3Operators 1 Arithmetic & Conc
Arithmetic OperatorsModulo OperatorExponentiation OperatorString ConcatenationOperator PrecedenceRecap - Simple Calculations6Project: Character Stats Disp
Welcome MessageDeclare Character Stats9Functions Basics
Declaring a FunctionCalling a FunctionFunctions with ParametersFunctions with Multiple ParamsThe 'return' StatementRecap - Area CalculatorPractice on your own: Online Lua compiler