Reputation: 633
I am new to lua and i am trying to extract the value form the right side of a splited string. I have this:
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+", "")
This gives me the string "ret=OK". What can i do so that from this string to only get "OK", something like: get all from right of the equal sign and remove it and the left part. And this i must do for all the strings from "data" variable. Thank you.
Upvotes: 1
Views: 1694
Reputation: 124
I would recommend the following:
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"
Note that the lua pattern makes the trailing comma optional (otherwise you miss the last keypair in the list).
Upvotes: 1
Reputation: 3113
Try this
for key, val in string.gmatch(data, "(%W*)=(%W*),") do
print(key.." equals "..val)
end
Upvotes: 0