2015-12-10 43 views
0

我是lua的新手,我試圖從分割字符串的右側提取值。我有這個:Lua從左側刪除字符

local t ={} 
local data = ("ret=OK,type=aircon,reg=eu,dst=1,ver=2_2_5,pow=1,err=0,location=0,name=,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,led=1,en_setzone=1,mac=FCDBB382E70B,adp_mode=run") 
for word in string.gmatch(data, '([^,]+)') do 
    t[#t + 1] = word 
end 
local first = t[1]:gsub("%s+", "") 

這給了我字符串「ret = OK」。 我能做些什麼,以便從這個字符串中只能得到「OK」,類似於:從等號的右邊獲取所有內容,並將其移除並將左邊的部分移除。而我必須爲「數據」變量中的所有字符串執行操作。謝謝。

+1

這幾乎是字面上來自lua手冊中關於['string.gmatch'](http://www.lua.org/manual/5.1/manual.html#pdf-string.gmatch)部分的示例。 –

回答

0

試試這個

for key, val in string.gmatch(data, "(%W*)=(%W*),") do 
    print(key.." equals "..val) 
end 
0

我想提出以下建議:

local data = 'ret=OK,type=aircon,reg=eu,dst=1,ver=2_2_5,pow=1,err=0,location=0,name=,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,led=1,en_setzone=1,mac=FCDBB382E70B,adp_mode=run' 

local t = {} 
for key, val in string.gmatch(data, '([^=,]*)=([^=,]*),?') do 
    t[key] = val 
end 

print(t['ret']) -- prints "OK" 
print(t['adp_mode']) -- prints "run" 

注意,LUA模式使後面的逗號可選的(否則你會錯過在列表中的最後一個密鑰對)。