Jump to content




Locals


  • This topic is locked This topic is locked
1 reply to this topic

#1 jay5476

  • Members
  • 289 posts

Posted 23 October 2013 - 10:48 PM

hi, i hope that i can teach some people about the benifits of using locals in your program

intro:
(this may be a bit to much for some to understand)
Well, in lua we have enviroments and in these enviroments we have all our variables
An enviroment is basiclly a table ( {ourVariable = "This is In My Enviroment" } ) set to a function ( files are called as functions ) .

When we run any program it is automaticlly setup to have its own enviroment which stores all of its variables, it also can acsess global( _G, for functions such as print() )
So if we have a program like
ourVariable = "some string i put here"
this will go into our enviroment and make ourVariable equal "some string i put here" but it will also leave it floating around for other functions and files to acsess which could break a program.

Now using locals we can make sure our variable only goes in our enviroment
example:
local ourVariable = "some string i put here"
this will go into our enviroment and make ourVariable equal "some string i put here" but it cannot be acsessed by other programs.

Now we can also use locals to make sure only that code block can acsess that variable
example:
local x = 1 -- local to our file
print(x) -- print the x local to the file
do -- start a code block
  local x = 5 -- define another x that is only local to the 'do' block
  print(x) -- print the x local to the 'do' block
end
print(x) -- if we print x again it will be the x that is local to the file
This shows that if locals cannot be used 'outside their scope' and this allows us to make them more 'private'

Local variables are also faster and they should be used as much as possible so that there wont be a need to worry about other programs interferring
Quotes


#2 MudkipTheEpic

  • Members
  • 639 posts
  • LocationWhere you'd least expect it.

Posted 24 October 2013 - 08:03 PM

One thing: Local variables aren't stored it the environment, they're stored in the call stack. (iirc)
local foo="bar"
print(getfenv()["foo"]==nil)
--#Output: true






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users