You will have to split the name into words, check the leading words for any useful adjectives and use the part of the name that comes after any adjectives as the name of the car.
Something like this:
local adjectives = {"big", "small", "red", "blue", "black"}
-- speed up search by turning it into a map of [word] = true
for _,v in ipairs(adjectives) do
adjectives[v] = true
end
local function strToNameAndAdjectives(str, adjectives)
local words = {}
local i = 1
local word
while true do
-- word: the word found at position i
-- j: a position after the word
local word, j = string.match(str, "([^%s]+)%s*()", i)
-- if word == nil or not table.find(adjectives, word) then
if word == nil or not adjectives[word] then
-- word was not recognized, it might be the name
return string.sub(str, i), words
else
-- word was recognized, add it to the list and search for the next one in the next loop iteration
table.insert(words, word)
i = j
end
end
end
print(strToNameAndAdjectives("big red mustang", adjectives)) --> "mustang", {"big", "red"}
print(strToNameAndAdjectives("small black beetle", adjectives)) --> "beetle", {"small", "black"}
print(strToNameAndAdjectives("blue pickup truck", adjectives)) --> "pickup truck", {"blue"}
After you have the name and adjectives, you search for the car named “mustang” and apply any appropriate changes corresponding to “big” and “red”.
Note that this code will fail if there are spaces surrounding the full name (it might attempt to search for the adjective " big"
, or a "mustang "
).
It also doesn’t flinch at e.g. “red big mustang” even though it sounds odd in English, although there is no reason for it not to accept this name.
As for truly Scribblenauts-like parsing, you should read about how they did it, if someone’s analyzed it yet. It can’t be that complicated, it just takes a really large dictionary.
Edit: while I normally scoff at using string.split
to get individual words from a string and joining the remainder back together like a noob making his first admin command script, here it sort of works because it also gets rid of insignificant whitespace in the name of the car. Someone might accidentally write
blue pickup truck
and get a blue "pickup________truck"
from the above code, which doesn’t exist - with string.split and table.concat, these extra spaces disappear.