2016-02-12 20 views
1

我的表在Lua如下表:字符串從CSV文件中讀取無法索引我在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  

我試圖強迫山坳[2]一個字符串,但仍然無法索引我的表作爲預期。


很抱歉的混亂,我寫了string.split功能,但忽略包含的上述它的代碼樣本。

我現在已經解決了這個錯誤。之前,我使用Matlab編寫了CSV文件,並將單元格格式錯誤地設置爲「數字」。將格式更改爲「文本」後,代碼將按預期工作。在我看來,一個非常奇怪的錯誤,導致這樣的事情:

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

lua 5.1或5.2中沒有string.split(),並且您沒有顯示csv行,也許它是用別的東西分隔的,而不是用逗號分隔的。 – Vlad

+0

不知道這是怎麼沒有錯誤... – EinsteinK

+0

嘗試做'print(string.byte('y'))'和'print(string.byte(col [2],1,#col [2])) ' – moteus

回答

2

如果要拆分一個字符串,你將不得不使用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」分隔任何字符,使用「。」分隔任何字符,...如果你想使用「。」作爲分隔符,使用「%」。