在读取文件时跳过某些部分

我正在使用 Lua 编写一个简单的程序,询问用户输入包含“ck”或“bv”之类内容的单词,这些单词必须在字典中,因此我有一个包含超过50000个字典单词的文件。当我输入文件中出现的单词时,它会显示我输了,我加了一行 print(line) 进行调试,发现它没有打印每个单词

例如:

enter image description here

文本文件

enter image description here

以下是读取文件的代码:

local words_file = io.open("words.txt", "r")
local words = {}
local contains = {"br", "gg", "in", "et", "ck", "q", "it", "el", "st", "es", "be"}
local input

math.randomseed(os.time())

for line in words_file:lines() do
  words[line] = words_file:read("*l")
  print(line)
end
print("已加载!")

以下是游戏的代码:

while true do
    local contain = contains[math.random(#contains)]
    print("请输入包含 \"" .. contain .."\" 的单词")
    input = io.read()
  if not (string.find(input, contain) and words[input:lower()]) then
    print("你输了!")
    break
  end
end
点赞
用户7396148
用户7396148

你不应该在你的循环中调用 words_file:read("*l"),这也导致你迭代器遍历整个文件从而导致你跳过一些行。

file:lines 的默认行为也是使用 l

返回一个迭代器函数,每次调用该函数时,根据给定的格式读取文件。当没有给出格式时,使用“l”作为默认值。

在循环变量 line 中已经有了这一行的值。

你只需要这样做:

for line in words_file:lines() do
  words[line] = true
  print(line)
end
2021-06-26 21:23:58