2015-02-12 66 views
1

我使用LUA读取文件中的数据,并且该代码如下所示,的Lua:读取文件

filename = "./temp/vtx_vel"..id..".dat" 
    file = io.open(filename, "r") 
    lineno = i + ni*j 
    local n = -1 
    for l in io.lines(filename) do 
     n = n + 1 
     if n == lineno then 
      vel = tonumber(l) 
      break 
     end 
    end 
    file:close() 

在外部文件中的数据正在改变。但是,当我在不同的步骤阅读这个文件时,我感到很奇怪,我得到了相同的值。这是为什么?

谢谢。

+0

您没有从您打开的文件句柄读取。您正在'io.lines'调用中打开一个新句柄,并且从不关闭它们。在循环中使用'file:lines()',看看问题是否消失。 – 2015-02-12 03:35:55

+0

谢谢你,我已经改变为“在file.lines()做l”,但得到错误:udf-vtx.lua:35:糟糕的参数#1到'行'(文件*预期,没有价值) – Kan 2015-02-12 03:39:52

+0

'file:lines()'不是'file.lines()'。您需要将其称为文件的“方法”(隐式地将'file'作为函数的第一个参数传递)。 – 2015-02-12 03:40:38

回答

0

阅读从我的经验,一个文件的最佳方法是只做到这一点:

local f = io.open(--your file here) 
local output = {} 
for each in f:lines() do 
    output[#output+1] = each 
end 

你的文件将被读入表output。 有其他需要注意的地方,除非你定义了一个模式,io.open()默认在“r”或读模式下打开一个文件。