Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to find nearest equivalent string in a table?

Hi there.

I'm coding here [as are we all] and I have a string.

local myString = "pla"

Now then, I want to take my string and find the nearest equivalent in this table

local myTable = {"player","playing","played","notplayed"}

I only want to list all closest options. So that'd mean it would run this:

for i,v in pairs(nearestEquivalent) do
	print(v) -- or in my case addToList(v)
end

and getting this:

> player
> played
> playing

Now then, how would I go about doing this.

I thought string.sub would work but that finds all the letters not just a selection.

I COULD make the string.sub run every time a letter was added or removed but that'd be unnecesarry code if theres another way

Bear in mind I'm trying to keep all this as clean as possible, with the BEST performance possible.

Thanks!

-Reece

1 comment

0

use string.match

1 answer

✓ Accepted answer

You can use the string.sub function, with the # operator to determine if the index matches up to your string like so:

local myTable = {"planet","planks","plaster","nevergoingtobechosen"};
local myString = "pla";

function nearestEq(s,t) --string, table
	local matches = {}; --Predefine a table of matches
	for _,v in pairs(t) do --Iterate through table provided
		if v:sub(1,#s) == s then --compare index with string
			matches[#matches+1] = v; --if it matches, insert to table
		end
		wait();
	end
	return matches; --give back the table of matches
end

print(table.concat(nearestEq(myString,myTable)," | "));
--> planet | planks | plaster

3 comments

0

What's table.concat?

0

table.concat concatenates the table's indexes according to it's hashmap

0

table.concat({1,2,3}) --> 123 | but table.concat({1,["2"]=2,3}) --> 13

This discussion is preserved as it was. New answers, comments, and votes are closed.