Learning Lua Step-By-Step (Part 3)

This entry is part 4 of 11 in the series Learning Lua Step-By-Step

Post Stastics

  • This post has 2185 words.
  • Estimated read time is 10.40 minute(s).

Advanced Strings and Data Structures

In the previous lessons, we covered the basics of Lua programming, including variables, conditional statements, functions, and loops. In this lesson, we’ll delve deeper into Lua’s string manipulation capabilities and explore the powerful data structures available in the language.

Advanced String Manipulation

Strings are a fundamental data type in Lua, and Lua provides a wide range of functions and operators to work with them. Let’s explore some of the more advanced string manipulation techniques.

Strings can use double or single quotes and [[ ]]

Lua strings can be enclosed in single quotes ('), double quotes ("), or using the [[]] syntax for multiline strings.

local singleQuote = 'This is a string in single quotes.'
local doubleQuote = "This is a string in double quotes."
local multiline = [[This is a
multiline
string.]]

Play with the various string definitions. Notice that if the word multiline in the multiline comment is tabs or spaced in, those characters are present in the output. Also, try adding single and double quotes to the other two strings. Notice that you get errors if you add the same kind of quote the string is terminated with. We will see shortly how we can handle this correctly.

Escape Characters

Lua supports various escape characters that allow you to include special characters within strings. These include \n for newline, \t for tab, \\ for backslash, \" for a double quote, and \’ for a single quote.

local message = "Hello,\nWorld!"
print(message)

There are many more escape sequences than I’ve shown here. You can read the Lua documentation for more. But these are the most commonly used.

This will output:

Hello,
World!

Getting the length of a string

You can use the # operator to get the length of a string.

local myString = "Lua is awesome!"
local stringLength = #myString
print(stringLength) -- Output: 15

Concatenating Strings

You can use the .. operator to concatenate strings.

local firstName = "John"
local lastName = "Doe"
local fullName = firstName .. " " .. lastName
print(fullName) -- Output: John Doe

Converting numerical values to strings

You can use the tostring() function to convert numerical values to strings.

local age = 30
local ageString = tostring(age)
print(ageString) -- Output: "30"

Escape characters in Lua Strings

In addition to the basic escape characters, Lua also supports the following:

  • \v for vertical tab
  • \a for alert (bell)
  • \b for backspace
  • \f for form feed

Converting to Upper and Lower

You can use the string.upper() and string.lower() functions to convert a string to uppercase or lowercase, respectively.

local myString = "Hello, World!"
local upperCase = string.upper(myString)
local lowerCase = string.lower(myString)
print(upperCase) -- Output: HELLO, WORLD!
print(lowerCase) -- Output: hello, world!

Getting a Sub-String

The string.sub() function allows you to extract a substring from a larger string.

local myString = "Lua is awesome!"
local substring = string.sub(myString, 5, 9)
print(substring) -- Output: "is aw"

ASCII

Lua provides functions to work with ASCII character codes. The string.byte() function returns the ASCII code of a character, and string.char() returns the character for a given ASCII code.

local charCode = string.byte("A")
print(charCode) -- Output: 65
local char = string.char(65)
print(char) -- Output: A

Printing Characters from Character codes

You can use the string.char() function to print characters from their ASCII codes.

local charCode1 = 65
local charCode2 = 66
local charCode3 = 67
print(string.char(charCode1, charCode2, charCode3)) -- Output: ABC

Repeating strings

The string.rep() function allows you to repeat a string a specified number of times.

local myString = "Lua "
local repeatedString = string.rep(myString, 3)
print(repeatedString) -- Output: Lua Lua Lua

Formatting Strings

Lua provides the string.format() function for formatting strings, similar to the printf() function in C.

local name = "John"
local age = 30
local message = string.format("Hello, %s. You are %d years old.", name, age)
print(message) -- Output: Hello, John. You are 30 years old.

Finding Substrings in a string with find() and match()

The string.find() function can be used to search for a substring within a larger string, while string.match() can be used to pattern matching.

local myString = "Lua is a powerful programming language."
local startIndex, endIndex = string.find(myString, "programming")
print(startIndex, endIndex) -- Output: 17 28

local pattern = "%a+"
local word = string.match(myString, pattern)
print(word) -- Output: Lua

Replacing a portion of a string with replace()

The string.gsub() function can be used to replace a substring within a string.

local myString = "I love Lua programming."
local newString = string.gsub(myString, "Lua", "Python")
print(newString) -- Output: I love Python programming.

By mastering these advanced string manipulation techniques, you’ll be able to perform complex text processing tasks and create more powerful Lua programs.

Lua’s Various Data Structures

Lua, known for its simplicity and versatility, offers a robust set of data structures that empower developers to efficiently organize and manipulate data. In this guide, we’ll explore Lua’s primary data structures and learn how to utilize them effectively in your programs.

Tables

Tables are Lua’s primary data structure and serve as associative arrays, lists, queues, stacks, and more. They can store key-value pairs and arrays with flexible indices.

Creating Tables

Tables are created using curly braces {}.

-- Creating an empty table
local emptyTable = {}

-- Creating a table with key-value pairs
local person = {
    name = "John",
    age = 30,
    city = "New York"
}

Accessing Table Elements

Table elements can be accessed using square brackets [] or dot notation.

-- Accessing elements using square brackets
print(person["name"]) -- Output: John

-- Accessing elements using dot notation
print(person.age) -- Output: 30

Adding and Modifying Elements

Elements can be added or modified by assigning values to keys.

-- Adding a new key-value pair
person.gender = "Male"

-- Modifying an existing value
person.age = 31

Iterating Over Tables

You can iterate over tables using the pairs() function.

for key, value in pairs(person) do
    print(key, value)
end

2. Arrays

Lua doesn’t have a distinct array type; instead, it uses tables to create arrays.

Creating Arrays

Arrays in Lua are created using numeric indices.

local numbers = {10, 20, 30, 40, 50}

Accessing Array Elements

Array elements are accessed similarly to table elements.

print(numbers[1]) -- Output: 10

Adding and Modifying Elements

You can add or modify array elements using numeric indices.

numbers[6] = 60 -- Adding a new element
numbers[2] = 25 -- Modifying an existing element

3. Sets

Sets are collections of unique elements.

Using Tables for Sets

Tables can represent sets by using elements as keys and true as values.

local mySet = {
    apple = true,
    banana = true,
    orange = true
}

Checking for Membership

You can check if an element is present in a set by accessing the corresponding key.

if mySet["banana"] then
    print("Banana is in the set")
end

4. Queues and Stacks

Queues and stacks can be implemented using tables.

Queues

Queues follow the FIFO (First In, First Out) principle.

local queue = {}

-- Enqueue
table.insert(queue, "first")
table.insert(queue, "second")

-- Dequeue
local item = table.remove(queue, 1)
print(item) -- Output: first

Stacks

Stacks follow the LIFO (Last In, First Out) principle.

ocal stack = {}

-- Push
table.insert(stack, "first")
table.insert(stack, "second")

-- Pop
local item = table.remove(stack)
print(item) -- Output: second

Lua’s data structures provide a versatile toolkit for managing and manipulating data efficiently. By mastering tables and understanding their flexibility, you can implement various data structures tailored to your specific needs. Whether you’re organizing key-value pairs, creating arrays, or implementing complex data structures like queues and stacks, Lua’s simplicity and power shine through its data structure capabilities. Experiment with these structures in your Lua programs to unleash their full potential and elevate your coding prowess.

Remember to save your Lua scripts and test them in the console or an integrated development environment (IDE) like Visual Studio Code or ZeroBrane Studio. Experimenting with the code and trying different variations will help you solidify your understanding of Lua’s advanced string manipulation capabilities.

Exercises

  1. String Manipulation:
    • Write a Lua script that takes a user’s full name as input and outputs the initials.
    • Create a program that converts a given temperature from Celsius to Fahrenheit and displays the result.
  2. Substring Extraction:
    • Write a Lua script that extracts the domain name from a given URL.
    • Create a function that takes a sentence as input and returns the longest word in the sentence.
  3. String Formatting:
    • Write a Lua script that formats a given number with commas as thousands separators.
    • Create a program that takes a date in the format “YYYY-MM-DD” and outputs it in the format “DD/MM/YYYY”.
  4. String Replacement:
    • Write a Lua script that replaces all occurrences of a word in a given text with a different word.
    • Create a program that removes all HTML tags from a given string.
  5. ASCII and Character Codes:
    • Write a Lua script that prints the ASCII values of the letters in your name.
    • Create a function that takes a string of characters and returns a new string with each character replaced by its corresponding ASCII value.
  6. Table Operations:
    • Create a Lua script that represents a table of student names and their corresponding ages. Prompt the user to enter a name and display the age of the student
    • Implement a Lua script that represents a table of countries and their capitals. Iterate over the table and print each country-capital pair in the format: “Country: Capital”.
  7. Array Manipulation:
    • Write a program that generates an array of 10 random numbers between 1 and 100. Calculate and print the sum of all the numbers in the array.
  8. Stack Implementation:
    • Implement a stack data structure using Lua tables. Provide functions for push, pop, and peek operations. Test the stack with a sequence of operations and print the stack contents after each operation.
  9. Queue Implementation:
    • Create a queue data structure using Lua tables. Implement enqueue and dequeue operations. Enqueue a series of elements, dequeue them, and print the dequeued elements.
  10. Combining Data Structures:
    • Design a program that combines multiple data structures (e.g., arrays, tables, etc.) to represent a simple address book. Allow users to add new contacts, search for contacts by name, and display the entire address book. Use a switch case statement to handle user input commands and functions to implement each command.

Conclusion

In this third lesson of the “Learning Lua Step-By-Step” series, you’ve expanded your Lua programming skills by exploring advanced string manipulation techniques and working with Lua’s powerful data structures.

You’ve learned how to leverage Lua’s string functions and operators to perform complex text processing tasks, such as string concatenation, substring extraction, character code manipulation, and string formatting. These skills will allow you to create more robust and flexible Lua programs that can handle a wide range of text-based inputs and outputs.

Moreover, you’ve gained a deeper understanding of Lua’s data structures, which will be the focus of our next lesson. Mastering Lua’s tables, arrays, and other data structures will empower you to build more complex and efficient programs that can store, organize, and manipulate large amounts of data.

As you continue your Lua learning journey, remember to practice the concepts covered in this lesson by working through the provided exercises. Hands-on experience is key to solidifying your understanding and preparing you for more advanced Lua programming techniques.

In the next lesson, we’ll dive into Lua’s Co-Routines. Stay tuned, and keep up the great work!

Resources

Online Tutorials and Documentation

  1. Lua Official Documentation: The official Lua documentation provides comprehensive information about Lua’s features, including tables and other data structures. Lua Documentation
  2. Lua Tutorial on TutorialsPoint: This tutorial offers a beginner-friendly introduction to Lua, covering basic syntax, data types, and data structures. Lua Tutorial

Books

  1. Programming in Lua (Fourth Edition) by Roberto Ierusalimschy: This book is considered the authoritative guide to Lua programming. It covers Lua’s syntax, features, and advanced topics, including data structures. Programming in Lua
  2. Lua 5.3 Reference Manual by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes: For a more in-depth understanding of Lua’s features, including tables and other data structures, this reference manual is a valuable resource. Lua 5.3 Reference Manual

Online Courses

  1. Lua Programming – Master the Basics by Udemy: This course provides a comprehensive introduction to Lua programming, covering fundamental concepts, including data structures. Lua Programming – Master the Basics
  2. Lua Programming by Codecademy: Codecademy offers an interactive course on Lua programming, which includes lessons on working with Lua’s data structures. Lua Programming

Community and Forums

  1. Lua Users Wiki: The Lua Users Wiki is a community-driven resource with tutorials, examples, and discussions about Lua programming. Lua Users Wiki
  2. Lua subreddit: Join the Lua subreddit to engage with other Lua enthusiasts, ask questions, and share your experiences working with Lua’s data structures. Lua subreddit

YouTube Channels

  1. The Coding Train: The Coding Train offers a variety of programming tutorials, including Lua, where you can learn about data structures and algorithms. The Coding Train
  2. Tech with Tim: Tech with Tim provides tutorials on various programming languages, including Lua. Check out their Lua tutorials for in-depth explanations of data structures. Tech with Tim

These resources offer a wealth of information and tutorials to help you deepen your understanding of Lua’s data structures and become proficient in utilizing them effectively in your Lua projects.

Series Navigation<< Learning Lua Step-By-Step (Part 2)Learning Lua Step-By-Step (Part 4) >>

Leave a Reply

Your email address will not be published. Required fields are marked *