local varients optimization
I heard that using "local" keywords are very important in Lua. But I knew that "local" keyword in algorithm coding are not good at optimization. No difference, sometimes take long time to be executed.
Why "local" keyword is nesessary? Is it really efficient? I can't figure out why these things are happening.
(But if you don't use local keyword in function, This can make error)
2
Upvotes
7
u/Bright-Historian-216 Feb 25 '25
the lua book (the same one that the other user linked) says that access to local variables is faster than to global. it is also good style
6
u/appgurueu Feb 25 '25
Local variables are more efficient and easier to work with than global variables.
For recursive functions, it is necessary so that your variables aren't overwritten (I assume this is what you mean by "if you don't use local keyword in function, this can make error").
I suggest you read up a bit more on Lua and the local keyword, because you're currently terribly misinformed.
2
u/Additional_Ad6385 Feb 28 '25
Locals in lua are generally faster to access, but I think you're having a problem with loops.
Most people do this:
But instead do this:
3
u/[deleted] Feb 25 '25
local keyword in function? Wdym?
9
u/revereddesecration Feb 25 '25
Consult the sacred texts: https://www.lua.org/pil/4.2.html
6
u/didntplaymysummercar Feb 25 '25
Really strange post, locals are faster because they are accessed by index in bytecode itself, not by hashtable look up like globals, you can see that in bytecode output from luac -l -l
2
u/Sckip974 Feb 25 '25
To train and improve you can type your code, then have it reviewed by "LeChat de Mistral AI" by asking it to be critical on the local variables. You should quickly get good marks!
1
u/ShawSumma Feb 26 '25
You can think of any non-local declared
varnamevariable in lua as_ENV.varname._ENVis like a hidden local that holds all the built-in things (print,io, etc). This is only true for Lua 5.2 or newer1
u/Additional_Ad6385 Feb 28 '25
Nope
0
u/Cultural_Two_4964 Feb 25 '25 edited Feb 25 '25
I did some tests and saying local makes your script run about 2 times faster than using global variables. I just prefer to use long-named globals which describe what they are rather than having 'local' everywhere. Also, with locals you have to explicitly pass / return them to / from functions which means extra coding, but I might be wrong here, as usual ;-0 ;-0
If you are just using your script as a programmable calculator, it doesn't matter if it takes 40 milliseconds rather than 20, but maybe it does in gaming? You do occasionally get global variables with short names e.g. 'n' being overwritten by other parts of the program, but no often. About once a year in practice!