Search code examples
lualua-table

Lua : Iterating through nested tables


I am trying to iterate through the table in lua, but somehow I am not able to print the values inside the table. It prints the address

SeriesPoint = {}

function SeriesPoint:new(x, y)
    local newSeriesPoint = {}
    setmetatable(newSeriesPoint, self)
    self.__index = self
    self.x = x
    self.y = y
    return newSeriesPoint
end

TestSeriesPoint = {}

table.insert(TestSeriesPoint , SeriesPoint:new(1,2))
table.insert(TestSeriesPoint , SeriesPoint:new(3,4))
table.insert(TestSeriesPoint , SeriesPoint:new(5,6))
table.insert(TestSeriesPoint , SeriesPoint:new(7,8))
table.insert(TestSeriesPoint , SeriesPoint:new(9,10))

for k,v in ipairs(TestSeriesPoint)
    print(k)
    print(v)
end

==============================

Output is : 

1
table: 0x55a66a277f20
2
table: 0x55a66a276e20
3
table: 0x55a66a276e90
4
table: 0x55a66a276f20
5
table: 0x55a66a276f60

when I tried with the below for loop,

for k,v in ipairs(TestSeriesPoint) do
    print(v.x)
    print(v.y)
end

My output is :

9
10
9
10
9
10
9
10
9
10

Can someone please guide me the right way to print proper values in for loop


Solution

  • For the first loop the v variable is the table because you are inserting a table you were returned from the new function and you're doing self.x = x and self.y = y and since you indexed self and defined self.x and self.y to be 9 and 10 last it prints 9 and 10 you should've done newSeriesPoint.x = x and newSeriesPoint.y = y