2

I've started fiddling a lot with lua recently, but I can't for my life figure this out.

Let's say I have a string that looks like this:

s = "a=x a=y b=z a=x"

I want to remove all duplicates and merge the values of duplicate keys into a table, so that I get:

t = {
a = {x,y},
b = {z},
}

I've been pondering about this for way too long. Any help is appreciated!

1 Answer 1

2

Try this:

s="a=x a=y b=z a=x"

s=s.." "
t={}
for k,v in s:gmatch("(.-)=(.-)%s+") do
        if t[k]==nil then t[k]={} end
        t[k][v]=true
end

for k,v in pairs(t) do
        for z in pairs(v) do print(k,z) end
end
Sign up to request clarification or add additional context in comments.

3 Comments

You make it seem so ridiculously easy. It seems to do what I want it to do - now i'll try to break it down to get a better understanding. Many thanks!
Quick question: (I have searched) How would I go about to print a nested value from this table. For example, print(t.a[1]) doesn't work.
@Easypeasy, that's exactly what for z in pairs(v) do print(k,z) end does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.