首页 > 解决方案 > 收到短信后 Lua 表值到变量

问题描述

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

我正在接收包含上表中单词之一的字符串数据。我想把那个合适的词放到一个变量中让我们说'x'。

因此,可以说其中一条消息是随机的,并且这次生成:“这是第一天,风很大”。我希望将“一”存储到变量 x 中。但是在收到“现在是第二天,阳光明媚”之后,我希望 x 是两个。同样在获得该变量集后,我需要精确从哪个表中获取“一”“二”或“三”。

标签: lua

解决方案


我不确定我是否正确理解您需要什么,但请检查此功能。

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_wordfunction 有两个参数:sence 和你的带有单词的表,函数返回两个值 - 第一个是找到的单词,第二个是包含这个单词的表。


推荐阅读