gogu
gogu

Reputation: 633

Lua remove characters from left

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

Answers (2)

Eric Roy
Eric Roy

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

warspyking
warspyking

Reputation: 3113

Try this

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

Upvotes: 0

Related Questions