Get item from list which name resemblances target string the most

I am looking to make something that returns an item from the list. An example below:

local List = {
	"slime",
	"skeleton",
	"zombie"
}

local function GetItem(str)
	
	--I don't know what to do here
	
	return Item
end

GetItem("s") --Will be: "skeleton"
GetItem("sl") --Will be: "slime"
GetItem("z") --Will be "zombie"
2 Likes

Okay so, I have a solution but it’d make s be slime.

What you could do is get a table of all strings containing the string and then the shortest one must be the most accurate. You could add more upon that but that is all that I can think of. Sorry if this does not work for you.

1 Like

It’s basically supposed to just get the string that’s first in the alphabetical order and includes the letters of the parameter ‘str’ at the beginning. I think this can be done via a loop, but there might be an easier way. I’ll try to figure something out.

2 Likes

I have only tested this on myself via a kick command that I’ve made but in retrospect it should function correctly.

local List = {
	"slime",
	"skeleton",
	"zombie"
}

local function ClosestString(List, String)
	local IncludesList = {}
	for i, Item in pairs(List) do
		string.lower(Item)
		if Item:match("^"..String) then
			table.insert(IncludesList, Item)
		end
	end
	
	table.sort(IncludesList) --Sorts the strings alphabetically
	
	return IncludesList[1] --This the first alphabetically with the string pattern at the beginning
end

ClosestString(List, "s") --Will be: "skeleton"
ClosestString(List, "sl") --Will be: "slime"
ClosestString(List, "z") --Will be "zombie"
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.