Lua表将值转换为变量,以在接收文本消息后获取

local table =
{
one = {"one", "two", "three"},
two = {"four", "five", "six"},
three = {"seven", "eight", "nine"},
}

我正在接收包含上述表中单词之一的字符串数据。 我希望将适当的单词放入一个变量中,比如'x'。

所以假设一条消息是随机生成的,这一次是:“今天是第一天,刮风了”。我希望将“one”存储到变量x中。但是在接收到“现在是第二天,阳光明媚”的消息后,我希望将x设置为出现的第二个单词“two”。在设置好这个变量之后,我还需要确定它是从哪个表中取出的:“one”、“two”或“three”。

点赞
用户5219197
用户5219197

我不确定我是否正确理解了你的需求,但是请查看这个函数。

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函数接受两个参数:句子和含有单词的表格,并返回两个值-第一个是找到的单词,第二个是包含该单词的表格。

2018-06-03 18:09:35