문제

If a user enters an invalid command then it returns the closest string to the user's input.

source = {"foo", "foo1"}
Suggest = function (input, source)
--do stuff
end

Thus when the user enters an undefined command "fo", for example it returns "foo". Sorry if this is poorly explained, in a hurry.

도움이 되었습니까?

해결책

You can use Levenshtein or Damerau–Levenshtein distance function to find commands closest to input. Here is a C library implementing both of these functions. Here is Levenshtein distance implemented in Lua.

The following function assumes distance is the distance function of choice. It takes optional radius argument to specify maximum distance from input to suggestion(you may not want to provide any suggestion if user entered something very strange, far from any existing commands). It returns an array of suggestions.

function suggest(input, source, radius)
   local result = {}
   local min_distance = radius or math.huge

   for _, command in ipairs(source) do
      local current_distance = distance(input, command)

      if current_distance < min_distance then
         min_distance = current_distance
         result = {command}
      elseif current_distance == min_distance then
         table.insert(result, command)
      end
   end

   return result
end

Note that this search algorithm is quite inefficient. It may or may not be a problem for you depending on number of commands and rate of searches.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top