Okay, grab yourself a coffee because what I am about to say might be difficult to understand at first.
You cannot directly modify the value of an argument in Lua.
This is because function arguments in Lua are passed by value.
To have the changes to an argument persist, you'd need to pass it by reference.
##About pass-by-value
When we say an argument is passed by value, we mean we are passing to a function the value of a variable. The called function cannot directly modify the outside variable itself because it only receives a copy of its value. Once the function returns, the copy goes out of scope and ceases to exist.
##About pass-by-reference
When we say pass-by-reference, we mean we actually give to the function a pointer, a special type of variable which holds the memory address of a variable. We say the pointer points to a variable.
The pointer itself is passed by value, and thus its value is copied, but since the pointer's value is the actual address to the memory location of the outside variable, we can modify the original variable by writing to that location.
However Lua does not allow the use of pointers.
There are multiple ways around this, however.
While Lua does not directly allows for the use of pointers, a similar behavior
can be achieved by using tables, which are passed by reference under the hood:
local t = {
a = 2
}
local function foo(par1)
par1.a = 4
end
print(t.a)
foo(t)
print(t.a)
Note that tables aren't the only type to be passed by reference. Functions, Coroutine (threads) and Userdata (Values passed to Lua from C or C++, such as any custom Roblox object, eg: Vector3, CFrame, Part...) are all also passed by reference.
This is not the best way to update an argument's value, however.
The best way to do it in Lua is to return its new value from the function and reassign the original variable.
local a = 2
local function foo(par1)
par1 = 4
return par1
end
print(a)
a = foo(4)
print(a)
Note that, in Lua, if you need to update multiple variables at once, you can return multiple values:
local a, b, c = 0, 0, 0
local function foo(par1, par2, par3)
par1 = 1
par2 = 2
par3 = 3
return par1, par2, par3
end
a, b, c = foo(a, b, c)
In C or C++, this isn't possible, hence the reason pointers exist in the first place.
You can also use upvalues, but it is less efficient than using parameters and return values:
local upvalue = 2
local function foo()
upvalue = 4
end
foo()
Hoped this helped.
Please make sure to mark my answer as accepted and optionally upvote; it helps both of us. :)
3 comments
That doesn't solve my problem. I need to update a different value every time
I did answer the question. I explained why updating arguments directly is impossible and provided solutions around it. The rest is up to you.
Righto. I've edited it a bit to work using returned values :) thx m8