【问题标题】:String read from CSV file cannot index my table in Lua从 CSV 文件读取的字符串无法在 Lua 中索引我的表
【发布时间】:2016-02-12 09:18:17
【问题描述】:

我在 Lua 中有如下表:

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] 强制转换为字符串,但仍无法按预期索引我的表。


抱歉,我写了一个 string.split 函数,但忽略了将它包含在代码示例中。

我现在已经解决了这个错误。早些时候,我使用 Matlab 编写了 CSV 文件,并且单元格被错误地格式化为“数字”。将格式更改为“文本”后,代码按预期工作。我认为一个非常奇怪的错误会导致这种事情:

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

【问题讨论】:

  • lua 5.1 或 5.2 中没有 string.split(),而且你没有显示 csv 行,可能是用其他东西分隔,而不是逗号。
  • 不知道这怎么没出错...
  • 试试print(string.byte('y'))print(string.byte(col[2], 1, #col[2]))

标签: lua lua-table


【解决方案1】:

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

请注意,拆分适用于我懒得自动逃脱的简单模式。在您的情况下这没问题,但是您可以使用“%w”按任何字符分割,使用“.”的任何字符,......如果你想使用“。”作为分隔符,使用“%.”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2015-03-15
    • 2021-04-12
    • 2014-02-14
    • 2021-07-13
    • 1970-01-01
    • 2014-12-04
    相关资源
    最近更新 更多