1
votes

I have table in Lua as follows:

tab = { y = 1, n = 2}

print(tab)
{
  y : 1
  n : 2
}

I am trying to index it with a string, which I have read from a CSV file. The following works as intended :

print(tab['y'])
1

However, this is not working as expected:

local file = io.open(label_file, "r")

for line in file:lines() do
    local col = string.split(line, ",")
    print(type(col[2]))               -> string
    print(col[2])                     -> y
    print( tab[ (col[2]) ])           -> nil
end    

I have tried coercing col[2] to a string, but will still not index my table as intended.


Sorry for the confusion, I wrote a string.split function but neglected to include it above in the code sample.

I have now resolved the error. Earlier, I had written the CSV file using Matlab and the cells were formatted incorrectly as 'numbers'. Upon changing the formatting to 'text', the code works as intended. A very odd error in my opinion, that leads to this kind of thing:

    print(type(col[2]))               -> string
    print(col[2])                     -> y
    print( col[2] == 'y')             -> false 
1
There's no string.split() in lua 5.1 or 5.2, and you didn't show csv lines, perhaps it is delimited with something else, not with commas. - Vlad
Not sure how this didn't error... - EinsteinK
try do print(string.byte('y')) and print(string.byte(col[2], 1, #col[2])) - moteus

1 Answers

2
votes

If you want to split a string, you'll have to use string.gmatch:

local function split(str,delimiter) -- not sure if spelled right
    local result = {}
    for part in str:gmatch("[^"..delimiter.."]+") do
        result[#result+1] = part
    end
    return result
end

for line in file:lines() do
    local col = split(line,",")
    print(col[2]) --> should print "y" in your example
    -- well, "y" if your string is "something,y,maybemorestuff,idk"
    print(tab[col[2]]) -- if it's indeed "y", it should print 1
end

Mind that split works with a simple pattern that I'm too lazy to escape automaticly. This is no problem in your case, but you could split by ANY character using "%w", ANY character using ".", ... If you want to use "." as delimiter, use "%.".