Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Question on how lua variables work?

Asked by 4 years ago

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?

0
b was assigned to a before a was nill, you cannot necessarily make reference variables like you can in C++ Ziffixture 6913 — 4y

2 answers

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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

0
Thank you! I think I understood more about the logic, I will do more searches JustHerezForQuestion 7 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

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.

0
Thank you for the help! You have clearified what's going on, but not exactly what I'm asking. I'm asking why "what's going on" happened, what's the logic behind it JustHerezForQuestion 7 — 4y
0
Ah sorry about that, glad you found the answer though! AlexTheCreator 461 — 4y

Answer this question