Page 1 of 2
What exactly are Locals?
Posted: Thu Jul 30, 2009 8:30 pm
by Jasoco
I can't seem to figure out what the benefits and limitations of Locals are. I tried Googling for a Lua site but it didn't really describe it helpfully.
What would the difference between these two be?
Code: Select all
variable = value
local variable = value
When should and shouldn't they be used?
Re: What exactly are Locals?
Posted: Thu Jul 30, 2009 8:31 pm
by TechnoCat
Sorry to reference you somewhere else, but...
http://www.lua.org/pil/4.2.html
Re: What exactly are Locals?
Posted: Thu Jul 30, 2009 8:51 pm
by Jasoco
Ah, that maks sense now. Thanks!
Re: What exactly are Locals?
Posted: Thu Jul 30, 2009 9:01 pm
by TechnoCat
I have a question now.
If I use
Code: Select all
foo=1
while foo do
local foo = foo
-- code goes here
end
Is there a way to modify the global variable in the same scope after I override a global with a local variable?
Re: What exactly are Locals?
Posted: Thu Jul 30, 2009 9:47 pm
by Robin
use _G.foo
Re: What exactly are Locals?
Posted: Thu Jul 30, 2009 10:38 pm
by bartbes
or using a dynamic name (which is surprisingly useful):
Re: What exactly are Locals?
Posted: Sun Aug 02, 2009 7:51 am
by Zorbatron
Man, how can you use lua and not know what local variable is XD?
Usually you only use local variables when you only need to store something temporarily. If you always use globals, not only will you be cluttering the global namespace (meaning there will be a lot of variable name conflicts), you are also using more memory than you should be.
Re: What exactly are Locals?
Posted: Sun Aug 02, 2009 8:01 am
by Jasoco
I never heard of Lua before I found Löve.
Re: What exactly are Locals?
Posted: Sun Aug 02, 2009 8:12 am
by Robin
Zorbatron wrote:Usually you only use local variables when you only need to store something temporarily. If you always use globals, not only will you be cluttering the global namespace (meaning there will be a lot of variable name conflicts), you are also using more memory than you should be.
Not to mention the speed advantages of using locals.
For example,
Code: Select all
function afunc()
local dothings = dothings
dothings()
dothings()
dothings()
dothings()
dothings()
end
will be faster than
Code: Select all
function afunc()
dothings()
dothings()
dothings()
dothings()
dothings()
end
Re: What exactly are Locals?
Posted: Sun Aug 02, 2009 8:18 am
by Zorbatron
@Robin - Its faster because accessing globals requires lua to use the hash-lookup algorithm on the global table correct?