Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a txt file with numbers in this pattern:

3 2 1 3
4 5 9 4
2 3 4 2
2 3 4 5

I have to read this data and convert it into a suitable data structure. This all needs to be done in Lua and I am quite brand new to the language. Please assist?

What I have tried:

The only thing I was able to do was to open, read and display the file but cannot store its data into a suitable data structure.

a = io.open ("grid.txt", "r")
io.input (a)
print(io.read("*all"))
io.close()
Posted
Updated 10-Dec-22 7:58am

If you are brand new to a language then the best place to start is at the language home page: The Programming Language Lua[^].
 
Share this answer
 
Try
Lua
local f = io.open("grid.txt")
assert(f, "unable to open the file")

-- collect the array
local arr = {}
for l in f:lines() do
  local row = {}
  for snum in l:gmatch("(%d+)") do
    table.insert(row, tonumber(snum))
  end
  table.insert(arr, row)
end

-- show the collected array
for i=1,#arr do
  for j=1,#arr[i] do
    print( string.format("arr[%d][%d] = %d", i, j, arr[i][j]))
  end
end
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900