Below is a Lua code snippet that defines functions for storing categories, titles, and their respective values, as well as retrieving them. The data structure used here is a nested table, where the outer table holds categories, each of which is a table of titles, and each title holds an array of three values.
lua
-- Define a table to hold all data
local dataStore = {}
-- Function to add a new category
function addCategory(category)
if not dataStore[category] then
dataStore[category] = {}
else
print("Category already exists.")
end
end
-- Function to add a title with three values to a category
function addTitle(category, title, value1, value2, value3)
if dataStore[category] then
if not dataStore[category][title] then
dataStore[category][title] = {value1, value2, value3}
else
print("Title already exists within this category.")
end
else
print("Category does not exist. Please add the category first.")
end
end
-- Function to retrieve the three values associated with a title under a category
function getValues(category, title)
if dataStore[category] then
if dataStore[category][title] then
return unpack(dataStore[category][title])
else
print("Title does not exist within this category.")
return nil
end
else
print("Category does not exist.")
return nil
end
end
-- Function to get all titles within a category
function getTitles(category)
if dataStore[category] then
local titles = {}
for title, _ in pairs(dataStore[category]) do
table.insert(titles, title)
end
return titles
else
print("Category does not exist.")
return nil
end
end
-- Example usage:
addCategory("Books")
addTitle("Books", "The Great Gatsby", 1925, 180, 2)
addTitle("Books", "1984", 1949, 328, 1)
local value1, value2, value3 = getValues("Books", "The Great Gatsby")
print("Values for 'The Great Gatsby':", value1, value2, value3) -- Should print: 1925, 180, 2
local titles = getTitles