2

我是 Lua 的新手,无法加载如下所示的 csv 文件:

22.74,22.99,23.47,24.44,26.39,30.27,38.05,53.6,84.7,146.9,271.3,520.1,1017.7,2012.89,4003.28,7984.06,15945.63,31868.75,63715.01,127407.52,254792.53

有 21 个值,用逗号分隔,行中没有空格。我有数百行。和数百个文件。我需要将这些行加载到 Lua 中的表格中,并能够使用简单的坐标(i,j)进行访问。我想调用每个数字 cs1、cs2、cs3... cs21 和每行一个数字。

我看过这个功能

    function readwaypoints(filename, numberofwaypoints)
  local file = io.open(filename)
  local waypoints = {}
  for n = 1, numberofwaypoints do
    local x, y, z
    x = file:read('*n')
    y = file:read('*n')
    z = file:read('*n')
    waypoints[#waypoints+1] = {['x'] = x, ['y'] = y, ['z'] = z}
  end
  file:close()
  return waypoints
end

但这似乎不起作用。或者我不知道如何访问数据。

谁能建议我解决我的问题?谢谢。

4

1 回答 1

3

它不起作用,因为*n需要输入中的数字并且会跳过空格,但不会跳过逗号。您将需要“吃”逗号file:read(1)或类似的东西。

function readwaypoints(filename, numberofwaypoints)
  local file = io.open(filename)
  local waypoints = {}
  for n = 1, numberofwaypoints do
    local x, y, z
    x = file:read('*n'); file:read(1) --<-- added
    y = file:read('*n'); file:read(1) --<-- added
    z = file:read('*n'); file:read(1) --<-- added
    waypoints[#waypoints+1] = {['x'] = x, ['y'] = y, ['z'] = z}
  end
  file:close()
  return waypoints
end

local waypoints = readwaypoints("waypoints.txt", 20)
print(waypoints[2].x == 24.44, waypoints[1].z == 23.47)

这为我打印true truewaypoints[<number of waypoints>].x您可以使用(或)访问这些元素y/z

于 2013-08-03T18:15:47.377 回答