Lua中从文件中读取数字到数组

我有一个文件,它长这样:

一些文字
184 3.7872  184 2.5076
185 3.7891  185 2.5063
186 3.7912  186 2.5042

我想跳过第一行,并将数据写入一个数组中。

我已经有:

local file = io.open("test.txt", "r");
local readFile = {}
for line in file:lines() do
   table.insert (readFile, line);
end

--初始化目标数组
local array = {}
for i=2,# readFile,1 do
   array[i-1] = {}
   for j=1,4,1 do
      array[i][j] = 0
   end
end

for i=2,# readFile,1 do
   --从readFile中拆分行
   --将数字写入目标数组
end

当我初始化数组时,似乎有一个我不理解的错误:

lua: script.lua:13: attempt to index a nil value (field '?')
stack traceback:
    script.lua:13: in main chunk
    [C]: in ?

有人可以帮帮我吗?另外,当我调用readFile[2]时,我得到的是184 3.7872 184 2.5076,我必须将其拆分并写入数组。我该怎么办?

点赞
用户88888888
用户88888888

以下方法能够实现目标,但效率很低:

local file = io.open("test.txt", "r");
local readFile = {}
for line in file:lines() do
   table.insert (readFile, line);
end

--初始化目标数组
local array = {}
for i=1,(#readFile)-1,1 do
   array[i] = {}
   for j=1,4,1 do
      array[i][j] = 0
   end
end

function string:split( inSplitPattern, outResults )
   if not outResults then
      outResults = { }
   end
   local theStart = 1
   local theSplitStart, theSplitEnd = string.find( self, inSplitPattern,     theStart )
   while theSplitStart do
      table.insert( outResults, string.sub( self, theStart,    theSplitStart-1 ) )
      theStart = theSplitEnd + 1
      theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
   end
   table.insert( outResults, string.sub( self, theStart ) )
   return outResults
end

local myTable = readFile[2]:split(" ")
for i = 1, #myTable do
   print( myTable[i] ) -- 这将会得到所需的输出结果
end

如果有更高效的方法,我也会很高兴。

2016-11-28 00:45:22
用户7170955
用户7170955

不需要过度复杂化。

local file = io.open("test.txt", "r");
local array = {}
for line in file:lines() do
    local t = {}
    for s in line:gmatch("%S+") do
        t[#t+1] = tonumber(s)
    end
    array[#array+1] = t
end

以下是我改动的一点不太好的解释。

local file = io.open("test.txt", "r");
-- local readFile = {} 这也不需要。
local array = {} -- 在此初始化它,更清洁、更简单。
for line in file:lines() do
    local t = {} -- 这是我们在数组中的行。
    for s in line:gmatch("%S+") do -- 遍历非空白块的字符串。请检查在线 Lua 模式匹配教程。
        t[#t+1] = tonumber(s)
    end
    array[#array+1] = t

    --[[ 如果你只想要数字,不关心换行符,只需执行

    for s in line:gmatch("%S+") do
        array[#array+1] = tonumber(s)
    end

    这样就可以了。]]
end

-- 删掉底部那部分,我们可以更有效地完成这件事。

一些提示,

  • Lua 数组/表不需要初始化,它们是动态的。
  • 错误来自于试图索引数组 [i],但你初始化了数组 [i-1]
  • for i=a, b, c do 循环中,只有未指定 c 的时候才需要指定它不是 1。所以 for i=1, #lines do 同样适用。
  • # 不是函数,它是索引(严格来说)。只是与它计数的东西配对看起来更干净而已。使用 #lines 而不是 # lines
2016-11-28 03:48:10