Lua - Tables as Dictionaries
Introduction
Dictionary is a data structure of key value pairs. A dictionary provides a way to get a value based on a simpler key. Consider the following example:
main.lua
-- dictionary of days
days ={[0]="Sunday", [1]="Monday", [2]="Tuesday",[3]="Wednesday",
[4]="Thursday", [5]="Friday", [6]="Saturday"}
-- print Tuesday
print(days[2])
Output
When you build and execute the above program, it produces the following result −
Tuesday
Here, we've implemented the dictionary using table, which is a versatile contruct in Lua. Let's look at various other interesting usecases and ways to create and manipute dictionaries in Lua.
Example - Creation of Dictionary with default indexes
As tables are associated with default indexes, we can create dictionary without using key-value notation as well.
main.lua
-- dictionary of days
days ={"Sunday", "Monday", "Tuesday","Wednesday",
"Thursday", "Friday", "Saturday"}
-- print Monday
-- as index starts from 1
print(days[2])
Output
When you build and execute the above program, it produces the following result −
Monday
Example - Creation of Dictionary with single index
As tables uses incremental indexes, we can utilize that feature as well as shown below.
main.lua
-- dictionary of days
days ={[0] = "Sunday", "Monday", "Tuesday","Wednesday",
"Thursday", "Friday", "Saturday"}
-- print Tuesday
print(days[2])
Output
When you build and execute the above program, it produces the following result −
Tuesday
Example - Creation of Dictionary with string based keys
As tables are associative, we can use string based keys as well as shown below.
main.lua
-- dictionary of days
days ={["Sun"] = "Sunday", ["Mon"]="Monday", ["Tue"]="Tuesday",["Wed"]="Wednesday",
["Thu"]="Thursday", ["Fri"]="Friday", ["Sat"]="Saturday"}
-- print Tuesday
print(days["Tue"])
Output
When you build and execute the above program, it produces the following result −
Tuesday
Example - Manipulation of Dictionary
We can insert, remove entries from a dictionary easily as shown below.
main.lua
-- dictionary of days
days ={["Sun"] = "Sunday", ["Mon"]="Monday", ["Tue"]="Tuesday",["Wed"]="Wednesday",
["Thu"]="Thursday", ["Fri"]="Friday", ["Sat"]="Saturday"}
-- remove Tuesday
days["Tue"] = nil
-- print nil
print(days["Tue"])
-- add Tuesday
days["Tue"] = "Tuesday"
-- print Tuesday
print(days["Tue"])
-- Modify an entry
days["Sun"] = "Holiday"
-- print Sunday
print(days["Sun"])
Output
When you build and execute the above program, it produces the following result −
Nil Tuesday Holiday