local table =
{
one = {"one", "two", "three"},
two = {"four", "five", "six"},
three = {"seven", "eight", "nine"},
}
我正在接收一个字符串数据,该数据包含上表中的一个单词。我想把合适的词放到一个变量中,比如'x‘。
因此,假设其中一条消息是随机生成的,并且这次生成了:“这是第一天,它有风”。我希望将“1”存储到变量x中,但在收到“现在是第二天,阳光普照”之后,我希望x是二。另外,在得到变量集之后,我需要精确地确定它是从哪个表中提取的“一”、“二”或“三”。
发布于 2018-06-04 02:09:35
我不确定我是否理解正确,你需要什么,但请检查此函数。
local table =
{
one = {"one", "two", "three"},
two = {"four", "five", "six"},
three = {"seven", "eight", "nine"},
}
local x = nil
local tab = nil
local sentence_1 = 'Now its day six and its sunny'
local sentence_2 = 'Now its day two and its sunny'
function search_word(sentence, words_table)
for key, words in pairs(words_table) do
for _, word in pairs(words) do
if string.match(sentence, word) then
return word, key
end
end
end
end
x, tab = search_word(sentence_1, table)
print(x, tab)
-- six two
x, tab = search_word(sentence_2, table)
print(x, tab)
-- two one
search_word
函数接受两个参数:语句和包含单词的表,函数返回两个值-第一个是找到的单词,第二个是包含该单词的表。
https://stackoverflow.com/questions/50666603
复制相似问题