string - 阅读时跳过文件的某些部分
问题描述
所以我在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
解决方案
您不应该words_file:read("*l")
在循环中调用,您还会导致迭代器在文件中前进,这会导致您跳过行。
file:lines的默认行为是也使用l
。
返回一个迭代器函数,每次调用它时,都会根据给定的格式读取文件。如果没有给出格式,则使用“l”作为默认值。
您已经从循环变量中的行中获得了值line
。
你只需要做
for line in words_file:lines() do
words[line] = true
print(line)
end
推荐阅读
- c++ - 将 D3D11 与 D2D1 组合时出现 D3D11 警告
- java - 错误:[Dagger/DependencyCycle] 使用 ActivityRetainedScoped 后发现依赖循环错误
- python - 通过 theta 对 numpy 数组进行 3D 旋转
- android - 华为 Mapkit 依赖错误:找不到 com.huawei.hms:maps:6.0.0.301。要求:项目:app
- keras - ValueError:没有为任何变量提供梯度:['conv2d_9/kernel:0', 'conv2d_9/bias:0', 'conv2d_10/kernel:0
- jacoco - 用于 maven 的 Jacoco 离线仪表
- azure - Webapp Webjob 日志未出现在存储容器中
- sql-server - 从 BigQuery 中的 TIMESTAMP 中提取早晚时间
- sql-server - Windows 用户拒绝 SQL Server 批量 openrowset 访问,但拒绝 sa
- angular - 角度路由 - 需要一个在每次 url 更改时触发的 observable