Menu
CoddyTech

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: 3

The 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: 5
challenge icon

Challenge

Easy

Create 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 count
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Lua compiler