Why I can use a function to set a table index using arguments but i can't set a varble passed as a parameter

Viewed 25

im new to lua (and programming ) I would like to know why I can use a function to set a table index using arguments but i can't set a varble passed as a parameter like this :

variable = 1
function f(v)
  v = 2
end
f(variable)
print(variable)
--prints 1

function f(t,i)
  t[i] = 2
end
f(table,index)
print(table[1])
--prints 2
1 Answers

From the Lua manual:

Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy

In your example variable is a number value which is none one of the mentioned types. Hence it is copied by value, not by reference.

So in

variable = 1
function f(v)
  v = 2
end
f(variable)

v is a copy of variable, local to f. Changing v does not affect variable.

In

function f(t,i)
  t[i] = 2
end
f(table,index)
print(table[1])

on the other hand, t is a reference to the same table, table refers to. Hence modifying t modifies the referred table.

Related