【问题标题】:Lua Table Value to Variable after reciving Text message收到短信后Lua表值到变量
【发布时间】:2018-06-04 02:28:05
【问题描述】:
local table =
{
one = {"one", "two", "three"},
two = {"four", "five", "six"},
three = {"seven", "eight", "nine"},
}

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

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

【问题讨论】:

  • 所以换句话说,你需要存储两个值,而不仅仅是单词。

标签: lua


【解决方案1】:

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

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

【讨论】:

  • break 仅退出内部 for,而不是两者。可能return 更适合这种情况。
  • 非常感谢,我在你给我答案之前编写了代码,但它花了 100 行。我需要在循环内循环中变得更好。你能给我指点关于这个的好纪录片吗?再次感谢
  • @OskarGarczyński ,我主要使用 Lua 官方文档 (lua.org/manual/5.3) 和 lua-users 页面 (lua-users.org/wiki)。理解嵌套循环的最佳练习是编写一个,并在这些循环中添加一些print。在上面的函数中,您可以在第一个循环中添加 print(key, word)。您可以将第二个循环更改为for k, word in pairs(words) do,并将 if 语句替换为 print(k, word)。这样,您将最好地了解两个循环如何遍历您的表。
猜你喜欢
  • 1970-01-01
  • 2020-06-05
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多