So I have a script down below
1 | local test = true |
2 |
3 | function change(test) |
4 | test = test |
5 | end |
6 |
7 | change( false ) |
8 | print (test) --returns true |
Will the above code set the parameter to itself since it has the same name as the variable on line one? Or will it set the test var on line 1 to false? I know this is a problem when I'm coding in java, typically I just use the this keyword to differentiate the parameter with the instance variable in the class. Let me know if I didn't explain this well enough, its kind of hard to express what I'm asking.
I cannot explain the inner workings of why this happens but you can check the lua manual.
This is my example of how I got it working, there may be better solutions:-
01 | test = true -- this must not be a local variable or getfenv will not pick it up as we are checking for 0 (global) |
02 |
03 | function change(test) |
04 | print (test) -- at the function level it returns false which is what we want |
05 | -- this shows the variable which are accessible from a global level |
06 | for i, v in pairs ( getfenv ( 0 )) do |
07 | print (i, " = " , v) |
08 | end |
09 |
10 | -- from the first print statement we can the assume that what test will do is set false = false as from my experience code will always use the same value for the same line of code |
11 |
12 | -- now we can attempt to find the global variables in this script, I have not tested if this finds "_G" variables but we know the name of the variable is test so we can then use the name test as a global variable to assign the value false. |
13 | getfenv ( 0 ) [ 'test' ] = test |
14 | end |
15 |
16 | change( false ) |
17 |
18 | print (test) --returns false |
Hope this help.
Hello.
Whenever you set parameters for a function, you are setting local variables to be used within that code block.
The following two code blocks are equivalent:
1 | function change(test) |
2 |
3 | -- other code |
4 | test = test |
5 | end |
1 | function change(...) |
2 | local test = ... |
3 |
4 | -- other code |
5 | test = test |
6 | end |
You are running into a scope problem. As I demonstrated in the second code block, whenever you set parameters for a function, you are creating local variables to be used inside of that function.
That means that when you call function change
with a parameter named test
, it creates a local variable named test
, and will not access a variable of the same name outside of the code block's scope.
1 | local test = true |
2 |
3 | function change(test) |
4 | test = test -- This sets a local variable named test equal to itself |
5 | end |
6 |
7 | change( false ) |
8 | print (test) --returns true |
In your above function, the test
that was declared first is not modified. However, if you change the naming scheme, it will modify the intended value:
1 | local test = true |
2 |
3 | function change(testValue) |
4 | test = testValue |
5 | end |
6 |
7 | change( false ) |
8 | print (test) --returns false |