Juanmol
Juanmol

Reputation: 11

join two string to one table in Lua

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?

Upvotes: 1

Views: 108

Answers (1)

lhf
lhf

Reputation: 72312

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

Upvotes: 1

Related Questions