LUA:Global and Local

From GMod Wiki

Jump to: navigation, search
Lua: Global and Local
Page white text.png Description:The differance between global and local functions, variables
link=User:KillerLUA Original Author:KillerLUA
Calendar.png 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.

Yarin Kaul Icon ArrowSquare32.png Back to KillerLUA Tutorials


Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox