100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

String Library in Lua

Master Lua's built-in string library -- immutable strings, extraction, case conversion, lightweight pattern matching, and formatted output.

Tables & DataBeginner9 min readJul 10, 2026
Analogies

The String Library and Immutable Strings

Lua strings are immutable byte sequences -- once created, a string's contents can never be changed in place, so every string library function that appears to 'modify' a string actually returns a brand-new string, leaving the original untouched. The library is available both as functions called through the string table, like string.upper(s), and as methods called directly on any string value using colon syntax, like s:upper(), because Lua sets the metatable of the string type so that __index points to the string table itself. Both forms are equivalent and interchangeable; s:upper() is simply sugar for string.upper(s).

🏏

Cricket analogy: A printed scorecard from a match can never be altered after the game -- correcting an error means printing a fresh scorecard, just as Lua strings are immutable and every 'modification' produces a brand-new string rather than editing the original.

Common String Functions

The string library covers the essentials: #s or string.len(s) gives the byte length, string.sub(s, i, j) extracts a substring using 1-based indices where negative numbers count from the end (so s:sub(-3) grabs the last three characters), string.upper(s) and string.lower(s) change case, string.rep(s, n) repeats a string n times, and string.byte(s, i) / string.char(...) convert between characters and their numeric byte codes. Because indices are 1-based and inclusive on both ends, string.sub('hello', 2, 4) returns 'ell', which trips up programmers coming from 0-based-indexed languages.

🏏

Cricket analogy: Extracting overs 16 through 18 from a full 20-over innings scorecard for highlight analysis is like string.sub(s, 16, 18) -- both endpoints inclusive, 1-based numbering matching how commentators actually call out over numbers.

Pattern Matching Basics

Lua patterns are a lightweight alternative to full regular expressions, using character classes like %d (digit), %a (letter), %s (whitespace), and %w (alphanumeric), plus quantifiers *, +, -, and ? to search text. string.find(s, pattern) returns the start and end indices of the first match, string.match(s, pattern) returns the matched substring (or captured groups if the pattern has parentheses), and string.gmatch(s, pattern) returns an iterator that yields every match in turn, making it the tool of choice for looping over all occurrences of a pattern in a string, such as pulling every word out of a sentence.

🏏

Cricket analogy: Scanning a full commentary transcript for every instance of a boundary call is like string.gmatch(text, 'FOUR!?') iterating every match in turn, while string.find just locates the first six or four in the innings.

Formatting and Substitution with string.format and gsub

string.format(fmt, ...) builds strings using C-style format specifiers -- %d for integers, %s for strings, %f or %g for floating point, %x for hexadecimal -- so string.format('Level %d: %s (%.1f%% complete)', 5, 'Forest', 42.5) produces a fully assembled string in one call rather than many concatenations. string.gsub(s, pattern, replacement, n) is the substitution workhorse: it finds every occurrence of pattern (or up to n occurrences if given) and replaces it with replacement, which can be a literal string, a table (looked up by the match), or a function (called with the match, whose return value becomes the replacement), and it also returns the count of substitutions made as a second return value.

🏏

Cricket analogy: Generating a graphic like 'Kohli: 82 off 61 (SR: 134.4)' from raw stats in one templated call is like string.format assembling a string from specifiers in one shot; swapping every player's real name for a nickname across a fan article is like string.gsub with a lookup table.

lua
local s = "Hello, Lua World!"

print(#s)                      --> 18
print(s:sub(1, 5))             --> Hello
print(s:sub(-6))               --> World!  (from 6th-from-end to end)
print(s:upper())                --> HELLO, LUA WORLD!
print(string.rep("ab", 3))     --> ababab

-- Pattern matching
local text = "Order #1042 shipped on 2026-07-10, Order #1043 pending"
for id in text:gmatch("#(%d+)") do
  print("Order ID:", id)
end
-- Order ID: 1042
-- Order ID: 1043

local year, month, day = text:match("(%d%d%d%d)%-(%d%d)%-(%d%d)")
print(year, month, day)        --> 2026  07  10

-- Formatting
local msg = string.format("Level %d: %s (%.1f%% complete)", 5, "Forest", 42.5)
print(msg)                     --> Level 5: Forest (42.5% complete)

-- Substitution with a function replacement
local censored, count = ("badword badword ok"):gsub("badword", "****")
print(censored, count)         --> **** **** ok   2

Lua patterns are not full regular expressions -- there is no alternation operator like | and no bounded repetition like {2,4}. They cover roughly 80% of everyday text-processing needs with a much simpler and faster implementation, but for genuinely complex matching (like validating a full email address against RFC rules), a dedicated regex library such as LPeg or lrexlib is a better fit.

  • Lua strings are immutable; every string library function returns a new string rather than modifying the original.
  • string.sub uses 1-based, inclusive indices, and negative indices count backward from the end of the string.
  • string.find locates a match's position, string.match returns the matched text (or captures), and string.gmatch iterates all matches.
  • Lua patterns use character classes like %d, %a, %s, %w and quantifiers *, +, -, ? and are simpler than full regular expressions.
  • string.format builds strings with C-style specifiers like %d, %s, %f, and %x in a single readable call.
  • string.gsub replaces matches with a literal string, a table lookup, or a function's return value, and returns the substitution count as a second value.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#LuaStudyNotes#StringLibraryInLua#String#Library#Lua#Immutable#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse