2015-11-15 61 views
2

我想将文本文件中的特定行存储到变量中。如何在变量中存储文本文件的特定行

file = io.open("words.lua", "r") 
randLine = math.random(1, 109583) 
local n = 0 
for l in io.lines("words.lua") do 
    n = n + 1 
    if n == randLine then 
    word = randLine 
    end 
end 

我想在randLine字符串存储在word。我怎样才能做到这一点?

+2

使用'word = l'而不是'word = randLine'。由于您在代码中不使用'file'变量,因此不需要第一行。 –

+0

如果我的答案帮助你,不要忘了点击旁边的绿色复选标记将其标记为已接受。 – warspyking

回答

0

行是一个迭代器,它返回行,而不是行号。

file = io.open("words.lua", "r") 
randLine = math.random(1, 109583) 
local n = 0 
for line in file:lines() do 
    n = n + 1 
    if n == randLine then 
    word = line 
    end 
end 
file:close() 
相关问题