Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Question on how lua variables work?

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?

1 comment

0

b was assigned to a before a was nill, you cannot necessarily make reference variables like you can in C++

2 answers

✓ Accepted answer

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

1 comment

0

Thank you! I think I understood more about the logic, I will do more searches

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.

2 comments

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

0

Ah sorry about that, glad you found the answer though!

This discussion is preserved as it was. New answers, comments, and votes are closed.