
- Lua Tutorial
- Lua - Home
- Lua Basics
- Lua - Overview
- Lua - Environment
- Lua - Basic Syntax
- Lua - Comments
- Lua - Print Hello World
- Lua - Variables
- Lua - Data Types
- Lua - Operators
- Lua - Loops
- Lua - Generic For
- Lua - Decision Making
- Lua - Date and Time
- Lua Functions
- Lua - Functions
- Lua - Multiple Results
- Lua - Named Arguments
- Lua - Default/Optional Arguments
- Lua - Closures
- Lua - Uses of Closures
- Lua - Local Functions
- Lua - Anonymous Functions
- Lua - Functions in Table
- Lua - Proper Tail Calls
- Lua Strings
- Lua - Strings
- Lua - String Concatenation
- Lua - Loop Through String
- Lua - String to Int
- Lua - Split String
- Lua - Check String is NULL
- Lua Arrays
- Lua - Arrays
- Lua - Multi-dimensional Arrays
- Lua - Array Length
- Lua - Iterating Over Arrays
- Lua - Slicing Arrays
- Lua - Sorting Arrays
- Lua - Merging Arrays
- Lua - Sparse Arrays
- Lua - Searching Arrays
- Lua - Resizing Arrays
- Lua - Array to String Conversion
- Lua - Array as Stack
- Lua - Array as Queue
- Lua - Array with Metatables
- Lua - Immutable Arrays
- Lua - Shuffling Arrays
- Lua Iterators
- Lua - Iterators
- Lua - Stateless Iterators
- Lua - Stateful Iterators
- Lua - Built-in Iterators
- Lua - Custom Iterators
- Lua - Iterator Closures
- Lua - Infinite Iterators
- Lua - File Iterators
- Lua - Table Iterators
- Lua - Numeric Iterators
- Lua - Reverse Iterators
- Lua - Filter Iterators
- Lua - Range Iterators
- Lua - Chaining Iterators
- Lua Tables
- Lua - Tables
- Lua - Tables as Arrays
- Lua - Tables as Dictionaries
- Lua - Tables as Sets
- Lua - Table Length
- Lua - Table Iteration
- Lua - Table Constructors
- Lua - Loop through Table
- Lua - Merge Tables
- Lua - Nested Tables
- Lua - Accessing Table Fields
- Lua - Copy Table by Value
- Lua - Get Entries from Table
- Lua - Table Metatables
- Lua - Tables as Objects
- Lua - Table Inheritance
- Lua - Table Cloning
- Lua - Table Sorting
- Lua - Table Searching
- Lua - Table Serialization
- Lua - Weak Tables
- Lua - Table Memory Management
- Lua - Tables as Stacks
- Lua - Tables as Queues
- Lua - Sparse Tables
- Lua Lists
- Lua - Lists
- Lua - Inserting Elements into Lists
- Lua - Removing Elements from Lists
- Lua - Iterating Over Lists
- Lua - Reverse Iterating Over Lists
- Lua - Accessing List Elements
- Lua - Modifying List Elements
- Lua - List Length
- Lua - Concatenate Lists
- Lua - Slicing Lists
- Lua - Sorting Lists
- Lua - Reversing Lists
- Lua - Searching in Lists
- Lua - Shuffling List
- Lua - Multi-dimensional Lists
- Lua - Sparse Lists
- Lua - Lists as Stacks
- Lua - Lists as Queues
- Lua - Functional Operations on Lists
- Lua - Immutable Lists
- Lua - List Serialization
- Lua - Metatables with Lists
- Lua Modules
- Lua - Modules
- Lua - Returning Functions from Modules
- Lua - Returning Functions Table from Modules
- Lua - Module Scope
- Lua - SubModule
- Lua - Module Caching
- Lua - Custom Module Loaders
- Lua - Namespaces
- Lua - Singleton Modules
- Lua - Sharing State Between Modules
- Lua - Module Versioning
- Lua Metatables
- Lua - Metatables
- Lua - Chaining Metatables
- Lua Coroutines
- Lua - Coroutines
- Lua File Handling
- Lua - File I/O
- Lua - Opening Files
- Lua - Modes for File Access
- Lua - Reading Files
- Lua - Writing Files
- Lua - Closing Files
- Lua - Renaming Files
- Lua - Deleting Files
- Lua - File Buffers and Flushing
- Lua - Reading Files Line by Line
- Lua - Binary File Handling
- Lua - File Positioning
- Lua - Appending to Files
- Lua - Error Handling in File Operations
- Lua - Checking if File exists
- Lua - Checking if File is Readable
- Lua - Checking if File is Writable
- Lua - Checking if File is ReadOnly
- Lua - File Descriptors
- Lua - Creating Temporary Files
- Lua - Working with Large Files
- Lua Advanced
- Lua - Error Handling
- Lua - Debugging
- Lua - Garbage Collection
- Lua - Object Oriented
- Lua - Web Programming
- Lua - Database Access
- Lua - Game Programing
- Lua Useful Resources
- Lua - Quick Guide
- Lua - Useful Resources
- Lua - Discussion
Lua - Tables
Introduction
Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.
Lua uses tables in all representations including representation of packages. When we access a method string.format, it means, we are accessing the format function available in the string package.
Representation and Usage
Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself.
--sample table initialization mytable = {} --simple table value assignment mytable[1]= "Lua" --removing reference mytable = nil -- lua garbage collection will take care of releasing memory
When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory. No separate memory is allocated separately for b. When a is set to nil, table will be still accessible to b. When there are no reference to a table, then garbage collection in Lua takes care of cleaning up process to make these unreferenced memory to be reused again.
Example - Using tables
An example is shown below for explaining the above mentioned features of tables.
main.lua
-- Simple empty table mytable = {} print("Type of mytable is ",type(mytable)) mytable[1]= "Lua" mytable["wow"] = "Tutorial" print("mytable Element at index 1 is ", mytable[1]) print("mytable Element at index wow is ", mytable["wow"]) -- alternatetable and mytable refers to same table alternatetable = mytable print("alternatetable Element at index 1 is ", alternatetable[1]) print("alternatetable Element at index wow is ", alternatetable["wow"]) alternatetable["wow"] = "I changed it" print("mytable Element at index wow is ", mytable["wow"]) -- only variable released and and not table alternatetable = nil print("alternatetable is ", alternatetable) -- mytable is still accessible print("mytable Element at index wow is ", mytable["wow"]) mytable = nil print("mytable is ", mytable)
Output
When we run the above program we will get the following output −
Type of mytable is table mytable Element at index 1 is Lua mytable Element at index wow is Tutorial alternatetable Element at index 1 is Lua alternatetable Element at index wow is Tutorial mytable Element at index wow is I changed it alternatetable is nil mytable Element at index wow is I changed it mytable is nil
Table Manipulation
There are in built functions for table manipulation and they are listed in the following table.
Sr.No. | Method & Purpose |
---|---|
1 |
table.concat (table [, sep [, i [, j]]]) Concatenates the strings in the tables based on the parameters given. See example for detail. |
2 |
table.insert (table, [pos,] value) Inserts a value into the table at specified position. |
3 |
table.remove (table [, pos]) Removes the value from the table. |
4 |
table.sort (table [, comp]) Sorts the table based on optional comparator argument. |
Let us see some samples of the above functions.
Example - Table Concatenation
We can use the concat function to concatenate two tables as shown below −
main.lua
fruits = {"banana","orange","apple"} -- returns concatenated string of table print("Concatenated string ",table.concat(fruits)) --concatenate with a character print("Concatenated string ",table.concat(fruits,", ")) --concatenate fruits based on index print("Concatenated string ",table.concat(fruits,", ", 2,3))
Output
When we run the above program we will get the following output −
Concatenated string bananaorangeapple Concatenated string banana, orange, apple Concatenated string orange, apple
Example - Insert and Remove
Insertion and removal of items in tables is most common in table manipulation. It is explained below.
main.lua
table.maxn = function( tableObject ) local maxIndex = 0 for k, _ in pairs( tableObject ) do maxIndex = math.max( maxIndex, k ) end return maxIndex end fruits = {"banana","orange","apple"} -- insert a fruit at the end table.insert(fruits,"mango") print("Fruit at index 4 is ",fruits[4]) --insert fruit at index 2 table.insert(fruits,2,"grapes") print("Fruit at index 2 is ",fruits[2]) print("The maximum elements in table is",table.maxn(fruits)) print("The last element is",fruits[5]) table.remove(fruits) print("The previous last element is",fruits[5])
Output
When we run the above program, we will get the following output −
Fruit at index 4 is mango Fruit at index 2 is grapes The maximum elements in table is 5 The last element is mango The previous last element is nil
Example - Sorting Tables
We often require to sort a table in a particular order. The sort functions sort the elements in a table alphabetically. A sample for this is shown below.
main.lua
-- initialize array of fruits fruits = {"banana","orange","apple","grapes"} -- iterate over fruits array to print each fruit for k,v in ipairs(fruits) do print(k,v) end -- sort the array using sort function table.sort(fruits) print("sorted table") -- print the sorted array for k,v in ipairs(fruits) do print(k,v) end
Output
When we run the above program we will get the following output −
1 banana 2 orange 3 apple 4 grapes sorted table 1 apple 2 banana 3 grapes 4 orange