Answered by
8 years ago Edited 8 years ago
Your Problem
2 | setStance(plrElement, stance) |
What you are trying to do is set the variable stance by passing it into this function. This is fine and dandy and will work as you expect when the variable is passed in by reference, but not when it is passed by value.
"Passing by Reference" vs "Passing by Value"
When you pass in an argument by reference, the parameter of the function then points to the same memory address as the argument you passed in. This means that when you make changes to the parameter inside the function, you also make changes to the variable outside the function.
However, when you pass in a variable by value it copies the data from your variable and assigns it to the parameter, giving it a different memory address. When you make changes to the parameter inside the function, the changes are not made to your variable you passed i in as it points to a different set of memory.
In Lua, we can not control how our variables work. There are default ways that each type of object act when you pass them into functions:
By Reference: tables, functions, threads, and userdata values
By Value: nil, boolean, number, string
Solution
Since your variable is nil, we are going to need to change the way that you function works. We need to return back the stance we want and to assign to the variable:
01 | function setStance(Element) |
02 | if stances [ Element ] then |
03 | local rng = math.random( 1 , 5 ) |
05 | if stances [ Element ] [ rng ] [ 1 ] then |
06 | return stances [ Element ] [ rng ] [ 1 ] |
15 | uis.InputBegan:connect( function (input, gameProcessedEvent) |
16 | if input.KeyCode.Name = = key and not gameProcessedEvent then |
17 | local plrElement = player:FindFirstChild( "Element" ).Value |
18 | local stance = setStance(plrElement) |