Fabio Guida
Fabio Guida

Reputation: 25

How to print single value of a table in lua

I can't figure out how to print a single value in tab2.

I'm trying to get the same result of when I print tab1.

I don't care about the order I just need to print a single pair(get the the key and the value), or pop it from the tab2 (with something like table.remove(tab1,1))

tab1= {{x=1},{y=2}}
tab2= {x=3, y=4}

for k,v in pairs(tab1[1]) do
    print(k,v)
end

for k,v in pairs(tab2) do
    print(k,v)
end

I'm having difficult with tables, I started study three days ago so I'm a principiant.

Thank you

Upvotes: 1

Views: 552

Answers (1)

Piglet
Piglet

Reputation: 28974

To print a single value from tab2 you do

print(tab2["x"]) or print(tab2["y"]).

Or short:

print(tab2.x) or print(tab2.y)

Thank you for your fast response. I need a way to do it when I don't know the key.

In order to get a single value from a table without providing a key you can use next

print(next(tab2))

Upvotes: 3

Related Questions