1

I have 2 strings:

fields="a,b,c,d,e"

values="1,2,,4,5"

I need a table, to get the pairs values like:

print(result.a) -> "1"

print(result.c) -> "" (or nil)

Is it possible?

csaar
  • 530
  • 5
  • 22
Juanmol
  • 11
  • 1
  • Do you have to work with these two strings or do you have the possibilty to use a lua table? For instance `local result = {a = 1, b = 2, c = '', d = 4, e = 5}`. – csaar Nov 05 '19 at 16:14
  • 1
    Yes, it is possible. See [this question](https://stackoverflow.com/questions/19907916/split-a-string-using-string-gmatch-in-lua) for starters. – Aki Nov 05 '19 at 16:30

1 Answers1

1

Here is an opportunity to exploit generators without a for loop. The code below runs two gmatch generators in tandem.

fields="a,b,c,d,e"
values="1,2,,4,5"

fields=fields.."," ; F=fields:gmatch("(.-),")
values=values.."," ; V=values:gmatch("(.-),")

result={}
while true do
    local k,v=F(),V()
    if k==nil or v==nil then break end
    result[k]=v
end

for k,v in pairs(result) do print(k,v) end
lhf
  • 70,581
  • 9
  • 108
  • 149