2

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

1
  • The loops are correct, it's the creating of SeriesPoint:new that isn't Commented Aug 11, 2022 at 6:35

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

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.