-1

Three loops but different results, why? (in lua 5.1)

1.

local a = {{b=5}, {b=4}}
for k,v in ipairs(a) do
   v.b = v.b + 1
end

2.

local a = {["b"]=5, ["bb"]=4}
for k,v in pairs(a) do
   v = v + 1
end

3.

local a = {5, 4}
for k,v in ipairs(a) do
   v = v + 1
end
  • 1 truly add 1 to all elements in table a, but 2&3 change nothing. why?
  • I use chunkspy to see the op code of these three blocks found that in first block it has settable op after alter the value in table a, but block 2or3 has not. Block 2&3 just do add 5 5 261 ; 1 (means add 1 to register 5 but not save the value to table), why this happen?
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jammyWolf
  • 2,743
  • 1
  • 13
  • 7

1 Answers1

1

The issue here, is that v in a k,v pair, is a reference to the value, not the key.

This means, that v= just modifies the local variable v and doesn't affect the table itself. You could, instead do a[k]=v+1, which carries the intended result for 2 and 3.

In the first case however, v is a reference to a table. And in lua, Modifying a table, or any reference to that table, is done to all references to the table. This question contains some helpful information on the topic of References Vs Values.

Community
  • 1
  • 1
ATaco
  • 421
  • 3
  • 11
  • thx! i got it, pairs and ipair just functions return ref to the table value, right? – jammyWolf Nov 29 '16 at 02:20
  • Yes, as stated in the answer. Once again, if you want to modify the table, `k` holds the key that returned that value, so `a[k] = something` will set that value for you, although `v` will not update. – ATaco Nov 29 '16 at 02:26
  • @jammyWolf It's good practice to accept the answer that solved your problem. – ATaco Nov 29 '16 at 05:05