LUA:Global and Local
From GMod Wiki
Lua: Global and Local |
Description: | The differance between global and local functions, variables |
Original Author: | KillerLUA |
Created: | October 14, 2010 |
Contents |
Introduction
In LUA, a variable or function can either be global or local. But what's the difference, and how will this affect access to my variable or function.
Down to business
Global
Global variables are set by simply setting a empty variable such as:
myrandomvar = 42 myrandomvar2 = Color(200,255,255)
This variable will then be available all througout garrys mod, it is shared across addons. However, don't think this will make a global variable on every machine running garrysmod. It will only work on the current garrys mod machine, all variables get cleared when garrys mod closes!
Local
Local variables can only be used inside the current scope of code, such as inside a function or loop.
(Fail)
function test() local myvar = 10 end myvar = 20
This will set the global variable 'myvar' to 20 and not the local version.
If you create a local variable outside functions, like this,
local myvar = 20 function test() end
It will be accessible all throughout the file. It's the same for an if statement, if you create a variable inside an if statement. It will still be available to the next scope, such as a function.
This will work for all the file:
if something == something then var = true end function whatisvar() if var == true then print("Var is true!") end end
Conclusion
I hope you have learnt something here, if you wan't to know more, you can visit the LUA tutorial series or view some of my tutorials here.