Question

I am trying to match three pieces of data on a line of text in a text file and store them in table elements. Each line looks something like this:

0.277719    0.474610    This
0.474610    0.721241    is
0.721241    1.063209    test

I have a local table to hold the line of text and I am trying to assign the data pieces as follows.

local data = {}
local file = io.open( "audio/audio.txt", "r" )
local i = 1
for line in file:lines() do
    data[i] = line
    data[i].start, data[i].out, data[i].name = string.match( line, '(%S+)%s*(%S+)%s*(%S+)' )
    i = i + 1
end

The data[i] = line part works just fine. The next line does not. All I get is the following error on the line data[i].start, data[i].out, data[i].name = string.match( line, '(%S+)%s*(%S+)%s*(%S+)' ):

attempt to index field '?' (a string value)

What am I doing wrong?

Was it helpful?

Solution

The error is in the line

data[i] = line

This line makes data[i] a string variable which cannot have other strings indexed to it. Change that line to:

data[i] = {}

and everything works fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top