阅读时跳过文件的某些部分

Skips some parts of the file while reading

所以我在 lua 中制作了一个简单的程序,要求您写一个包含“ck”或“bv”之类的单词,显然这些单词必须在字典中,所以我有一个 fille字典上有超过 50,000 个单词,问题是当我输入文件上的单词时它说我输了,我放了一个打印(行)进行调试所以我可以看到发生了什么,我注意到它没有打印每个字

示例:

文本文件

这是读取文件的代码:

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("Loaded!")

这是游戏代码:

while true do
    local contain = contains[math.random(#contains)]
    print("Write a word that contains \"" .. contain .."\"")
    input = io.read()
  if not (string.find(input, contain) and words[input:lower()]) then
    print("lol u bad")
    break
  end
end

你不应该在你的循环中调用 words_file:read("*l"),你还导致迭代器在导致你跳过行的文件中前进。

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

Returns an iterator function that, each time it is called, reads the file according to the given formats. When no format is given, uses "l" as a default.

您已经在循环变量 line.

的行中获得了值

你只需要做

for line in words_file:lines() do
  words[line] = true
  print(line)
end