Search code examples
csvluaknn

insert Knn csv into table LUA


I'm trying to load csv containing knn data (3 columns no names)
e.g

4   3   a
1   3   a
3   3   a
4   5   b

I have been able to load the file into a string.

When I try to move that into a table I get no errors, however when I print the table to screen I get values of nil.

I tried changing contents of file which gives the same result and if changed to (knn_data) I get the path address of the csv in all keys.

I'm trying to get the csv data to appear within the indexed table and in its 3 columns.

Here is the code:

--load kNN file.

local knn_data = system.pathForFile("knn.csv", system.ResourceDirectory)
local file, errorString = io.open(knn_data, "r")

if not file then
    print("File Error: File Unavailable")
else
    local contents = file:read("*a")
    print(contents)
    io.close(file)
end
file = nil

-- load data into table
dataset = {}
for line in io.lines(knn_data) do
    dataset[#dataset+1] = (contents)

Previously attached screenshot of code


Solution

  • ...

    else
      local contents= file:read("*a")
      print(contents)
    --io.close(file)
    end
    

    contents is a local variable in your else statement. Outside of it, contents is nil.

    dataset = {}
    for line in io.lines(iknn_data) do
      dataset[#dataset+1] = (contents)
    

    So dataset[#dataset+1]= (contents) is equivalent to dataset[#dataset+1]= nil

    Within that generic for loop, line contains the line read from the file. So actually you should work with that.