首页 > 解决方案 > 阅读时跳过文件的某些部分

问题描述

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

例子:

在此处输入图像描述

文本文件

在此处输入图像描述

这是读取文件的代码:

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

标签: stringfilelua

解决方案


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

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

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

您已经从循环变量中的行中获得了值line

你只需要做

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

推荐阅读