从 CSV 文件读取的字符串无法在 Lua 中索引我的 table

String read from CSV file cannot index my table in Lua

我在Lua中有table如下:

tab = { y = 1, n = 2}

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

我正在尝试使用从 CSV 文件中读取的字符串对其进行索引。以下按预期工作:

print(tab['y'])
1

但是,这没有按预期工作:

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    

我已尝试将 col[2] 强制转换为字符串,但仍无法按预期为我的 table 编制索引。


抱歉造成混淆,我写了一个 string.split 函数但忽略了将其包含在上面的代码示例中。

我现在已经解决了这个错误。早些时候,我使用 Matlab 编写了 CSV 文件,但单元格的格式不正确,如 'numbers'。将格式更改为 'text' 后,代码按预期工作。我认为这是一个非常奇怪的错误,导致了这种事情:

    print(type(col[2]))               -> string
    print(col[2])                     -> y
    print( col[2] == 'y')             -> false 

如果要拆分字符串,则必须使用 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

请注意,split 使用一种我懒得自动转义的简单模式。这在您的情况下没有问题,但您可以使用“%w”按任何字符拆分,使用“。”的任何字符,...如果您想使用“。”作为分隔符,使用“%.”。