【发布时间】: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]))