Files
simple-makes-complex/mods/SYSTEM/HelperLib/src/Lib/matchItemDescription.lua

71 lines
2.1 KiB
Lua

local ipairs = ipairs
local tableInsert = table.insert
local stringMatch, stringLower = string.match, string_utf8.lower
local coreGetTranslatedString = core.get_translated_string
---Checks whether an item's name and description match a given pattern.
---
---Use it to create unconventional lists based on text searches.
---
---
---For example:
---```lua
------A function for determining a list of crafts that match a text-based search query
---local function getMathedCrafts(crafts, pattern)
--- local pattern = stringLower(pattern)
--- local matchedCrafts = {}
---
--- for _, craft in ipairs(crafts) do
--- if Smc.matchItemDescription(ItemStack(craft.output):get_name(), pattern) then
--- tableInsert(matchedCrafts, craft)
--- end
--- end
---
--- return matchedCrafts
---end
---```
---
---**Note**: to obtain standard lists of items, use: `Smc.getMathedItems()`
---
---@param itemName ItemStackString
---@return boolean
function Smc.matchItemDescription(itemName, pattern)
local ItemStack = ItemStack(itemName)
-- Only items registered via the `Item` wrapper class have an `_title` field.
-- Therefore, `short_description` is used as a fallback title.
local itemTitle = ItemStack:get_definition()._title or ItemStack:get_short_description() or ''
local ruName = stringLower(coreGetTranslatedString('ru', itemTitle))
local enName = stringLower(coreGetTranslatedString('en', itemTitle))
if stringMatch(itemName, pattern) or
stringMatch(ruName, pattern) or
stringMatch(enName, pattern) then
return true
else
return false
end
end
local matchItemDescription = Smc.matchItemDescription
---Returns a list of items whose name or description matches a pattern.
---
---Use this method to retrieve lists of items based on a text search.
---@param items ItemStackString[]
---@param pattern string
---@return ItemStackString[]
function Smc.getMathedItems(items, pattern)
local pattern = stringLower(pattern)
local macthedItems = {}
for _, itemName in ipairs(items) do
if matchItemDescription(itemName, pattern) then
tableInsert(macthedItems, itemName)
end
end
return macthedItems
end