Lua - Tables as Sets
Introduction
A Set is a colletion which cannot have duplicate elements. There are many use cases of a Set like−
Reserved keywords
Unique numbers
Mathematical Operators
and so on...
In Lua, we can create a set using table construct very easily as a table uses associative key values. For example, if we want to make a check that a expression should not be using any of the given reserved keyword then we can create a table or reserved keywords as indexes and corresponding value as true.
reserved = {
["while"] = true, ["end"] = true, ["function"] = true, ["local"] = true,
["for"] = true, ["then"] = true, ["do"] = "true"
}
Now we can make a check on reserved keywords using following syntax.
for index, word in ipairs(allwords) do
-- if word is present in reserved set
if reserved[word] then
print(word, "is a reserved keyword.")
break
end
-- do the regular processing
end
Complete example of Set of Reserved keywords
Now let's see the complete code in action.
main.lua
-- set of reserved keywords
reserved = {
["while"] = true, ["end"] = true, ["function"] = true, ["local"] = true,
["for"] = true, ["then"] = true, ["do"] = "true", ["if"] = "true"
}
-- collection of words
allwords = {"value", "=", "30", "if", "index", "=", "4", "and", "error", "=", "1"}
-- iterate through all words
for _, word in ipairs(allwords) do
-- if word is present in reserved set
if reserved[word] then
print("Error: ", word, "is a reserved keyword.")
return
end
-- do the regular processing
end
print("all good")
Output
When the above code is built and executed, it produces the following result −
Error: if is a reserved keyword.
Function to create a Set
We can create a function which can give the Set implementation as required above. See the syntax below:
-- function to return a set on given values
function Set (list)
-- initialize the empty set
local set = {}
-- iterate over values
for _, value in ipairs(list) do
set[value] = true
end
-- return the set
return set
end
Now we can call the above function and get the set of prime numbers as shown below:
keywords = { "2", "3", "5", "7", "11", "13", "17", "19"}
primeNumbers = Set(list)
Complete example of Search of Prime Numbers
Now let's see the complete code in action.
main.lua
-- function to return a set on given values
function Set (list)
-- initialize the empty set
local set = {}
-- iterate over values
for _, value in ipairs(list) do
set[value] = true
end
-- return the set
return set
end
list = { "2", "3", "5", "7", "11", "13", "17", "19" }
primeNumbers = Set(list)
-- collection of words
allwords = {"1","12","13","4","51","16","18" }
-- iterate through all words
for _, word in ipairs(allwords) do
-- if word is present in primae numbers
if primeNumbers[word] then
print("A Prime Number found: ", word)
return
end
-- do the regular processing
end
print("all good")
Output
When the above code is built and executed, it produces the following result −
A Prime Number found: 13