Inksaver

Variable Scope Demo (Lua)

Jun 7th, 2020
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.56 KB | None | 0 0
  1. --[[
  2.     In Lua variables declared outside of any function/procedure/loop etc are
  3.     available to the whole script.
  4.     you should use the local keyword on all variables declared, as this makes them LOCAL to the
  5.     entire script (effectively global), but not available to other scripts in the project.
  6.    
  7.     They are READ/WRITE inside a function/procedure (unlike Python)
  8.  
  9.     Variables declared inside functions/procedures/loops SHOULD be local to that code block.
  10.     This only occurs if the local keyword is used, They are deleted when the code block is ended.
  11.     If you decare a variable inside a function WITHOUT the local keyword, it is still available to the rest
  12.     of the script, just as if it were declared outside the function.
  13.     This is unique to Lua.
  14. ]]
  15. local globalDemoVariable = "Hello World" -- global to the whole of this script, not available to other scripts
  16.  
  17. function luaScopeDemo()
  18.     print(globalDemoVariable)
  19.     globalDemoVariable = "Goodbye" -- unlike python this variable can be changed here
  20.     print(globalDemoVariable)
  21.    
  22.     local localDemoVariable = "this is a local string variable" -- local to this function. Deleted as soon as procedure has completed
  23.     --localDemoVariable = "this is also a global string variable" -- no local keyword: still available after procedure has completed
  24.     print(localDemoVariable)
  25. end
  26.  
  27. function main()
  28.     luaScopeDemo()
  29.     print(localDemoVariable) -- no longer available as was local to the procedure, so nil is printed. Does NOT cause error as in C#/Python
  30.     io.write("Enter to quit")
  31.     io.read() -- stop console closing
  32. end
  33.    
  34. main()
Add Comment
Please, Sign In to add comment