Lua - Sparse Lists



A sparse list is a list where most of the elements are either nil or have some default value. In Lua, we can define a sparse list effectively using tables. A Lua table contains key-value entries and allocates memory only if key-value pairs are actually present. In this chapter, we're exploring ways to work with sparse lists in Lua.

Representing a Sparse List

We can create a list by using specific indices based keys and other indices will remained unassigned.

main.lua

-- create an empty table to represent a list
local sparseList = {}

-- Use specific indices to assign values
sparseList[1] = "apple"
sparseList[3] = "banana"
sparseList[10] = "mango"

-- prints apple
print(sparseList[1])   
-- prints nil as 2 is not assigned
print(sparseList[2])   
-- prints banana
print(sparseList[3]) 
-- prints nil
print(sparseList[5]) 
-- prints mango
print(sparseList[10])

Output

When we run the above code, we will get the following output−

apple
nil
banana
nil
mango

Iterating a Sparse List

As a sparse List is having multiple unassigned indices, standard sequential iteration using #, for loops might not work. We can use pairsto iterate a sparse list.

main.lua

-- create an empty table to represent a list
local sparseList = {}

-- Use specific indices to assign values
sparseList[1] = "apple"
sparseList[3] = "banana"
sparseList[10] = "mango"

for key, value in pairs(sparseList) do
   print(string.format("Index: %s, Value: %s", key, value))
end

Output

When we run the above code, we will get the following output−

Index: 1, Value: apple
Index: 3, Value: banana
Index: 10, Value: mango

As ipairs() works on indices, using ipairs() may not work on sparse lists as shown below:

main.lua

-- create an empty table to represent a list
local sparseList = {}

-- Use specific indices to assign values
sparseList[1] = "apple"
sparseList[3] = "banana"
sparseList[10] = "mango"

for index, value in ipairs(sparseList) do
   print(string.format("Index: %s, Value: %s", index, value))
end

print(string.format("Length: %s", #sparseList))

Output

When we run the above code, we will get the following output−

Index: 1, Value: apple
Length: 1

ipairs() works with contingous indexes. It stops at first missing numerical or non-numerical key. Using # is not recommended on a sparse list.

Advertisements