Hello, say I want to define input
to a variable but I'm kinda skeptical about which is the optimal way of doing this...
A;
local key --variable defined only once which is in the start of playtest UIS.InputBegan:Connect(function(input, gameProccessed) key = input end
or, B:
UIS.InputBegan:Connect(function(input, gameProccessed) local key = input --variable being defined everytime the event fires end
I think A is the go-to when key
is to be accessed outside of InputBegan
's scope but what if it's only to be used inside?
Tips and explanations are greatly appreciated! <3
I’m not amazingly good with the lower levels of languages, but I am 90% sure that variable assignment only takes time at compile time. which is to say, when it is converted to bytecode, the memory for variables is already preallocated. not only that, but reused variables can be detected and optimized automatically, making no difference! in fact, the second one is even better because even after optimization the variable is found in an enclosed scope and it does not affect future processes with extra variables to look through. more importantly it is just easier to read.
note that this kind of thing is so miniscule that just having the variable outside and gobbling memory is slower than assigning it
you should never worry about variable assignments unless you are directly assigning memory yourself. which you do not do in lua.
edit: I would also like to mention which I find pretty neat, that the same goes for mathematical operations that only use constants. for example, you will never need to store Vector3.new(0, 1, 0) or math.sqrt, you could actually use than IN your equation, because they will be automatically converted to constants only once!
They are the same if the value are being set, for example, a = 5
. If you want to make the variable update everytime per scope, use B, otherwise, use A.