So I know that lua is pass by reference, because
local a = {} local b = a b[1] = true print(a[1]) --true
Meaning, if I change b
will change a
and changing a
will change b
. But does that only apply for inserting stuff into tables? because if I set a to something else, I'd expect b to change as well, but no.
local a = {} local b = a a = nil print(b) --stills prints the table
And for numbers
local a = 2 local b = a b = b*2 print(b,a) --4, 2
I'm confused, can someone explain more?
your certainly right about pass by reference, but keep in mind that pass by reference only applies to tables, and userdata.
now the way pass by reference works in Lua is unlike in C++, a variable holds reference to an object, whenever you do something like access a field, it indexes the value of the variable.. so its kinda like there's 2 entities to a variable, the variable and the value it holds reference to.. whenever you want to access the value, you have to do it via the variable, but the variable it's self is a separate entity..
because the variable is a seperate entity, you can assign it a different value, and this wouln't affect the current value.. whenever a value doesn't have variable entity, the Lua Garbage collector releases the memory that it holds
and this why when you assign 2 variables the same value, you can change one of the variables without impacting the other, b/c they are separate entities
I am by no means an expert (or even good) at scripting but I think that...
The script reads down the page so:
For the first block of code you have effectively just replaced the letter b on line 3 with an a, which works fine.
In the second block of code the script has read that b = a (a table) before a is declared as nil. B has not been updated and thus remains as the table described by the first a. Remember, the script reads down the page.
The third block of works as the first block did. you have effectively replaced the b's with a's on line 3.