You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua读取单词文件时出现跳行导致有效单词输入被判定错误如何解决?

问题根因

文件读取逻辑存在重复读行的错误:

  • for line in words_file:lines() 迭代器本身会在每次循环时自动读取文件的下一行赋值给line变量
  • 循环体内额外调用的words_file:read("*l")会再读取一行,导致每次循环消耗2行内容,一半单词被跳过。同时你将第一次读取的行作为键、第二次读取的行作为值存入words表,表结构也不符合存在性校验的预期。

修复方案

修改读取逻辑,取消多余的读行调用,直接用读取到的行做存在性标记即可,顺便统一转小写存储,避免大小写匹配问题:

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
  -- 统一转小写存储,和输入时的lower处理对应
  words[line:lower()] = true
  print(line)
end
words_file:close() -- 读取完成后关闭文件是良好习惯
print("Loaded!")

修改后所有单词都会被正常加载到表中,输入存在的单词就不会再误判输了。

内容的提问来源于stack exchange,提问作者arcioko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 06:00:05