mehdi
mehdi

Reputation: 13

why this function in this class doesn't work correct in lua?

I run this code in lua:

cal = {num1 = 0, num2 = 0, num3 = 0,num4 = 0,num5 = 0,num6 = 0}
function cal:new (n1,n2,n3,n4,n5,n6)
    local self = {}
    setmetatable(self,cal)
    self.num1 = n1
    self.num2 = n2
    self.num3 = n3
    self.num4 = n4
    self.num5 = n5
    self.num6 = n6
    return self
end
ea = cal:new(1,2,3,4,5,6)

ae = cal:new(7,8,9,10,11,12)

for k,va in pairs(ea) do print(va) end
for k,va in pairs(ae) do print(va) end

and this is the output:

1
2
5
6
3
4
7
8
11
12
9
10

why this numbers has been messed up???

Upvotes: 1

Views: 81

Answers (2)

luther
luther

Reputation: 5564

Lua does not store table keys in any particular order. One way to print fields in order would be to add another method:

function cal:print()
  print(self.num1)
  print(self.num2)
  print(self.num3)
  print(self.num4)
  print(self.num5)
  print(self.num6)
end

Upvotes: 0

lhf
lhf

Reputation: 72422

pairs traverses a table in an unspecified order.

The manual says

The order in which the indices are enumerated is not specified, even for numeric indices.

(That's in the entry for next, on which pairs is based.)

Upvotes: 1

Related Questions