Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- In Lua variables declared outside of any function/procedure/loop etc are
- available to the whole script.
- you should use the local keyword on all variables declared, as this makes them LOCAL to the
- entire script (effectively global), but not available to other scripts in the project.
- They are READ/WRITE inside a function/procedure (unlike Python)
- Variables declared inside functions/procedures/loops SHOULD be local to that code block.
- This only occurs if the local keyword is used, They are deleted when the code block is ended.
- If you decare a variable inside a function WITHOUT the local keyword, it is still available to the rest
- of the script, just as if it were declared outside the function.
- This is unique to Lua.
- ]]
- local globalDemoVariable = "Hello World" -- global to the whole of this script, not available to other scripts
- function luaScopeDemo()
- print(globalDemoVariable)
- globalDemoVariable = "Goodbye" -- unlike python this variable can be changed here
- print(globalDemoVariable)
- local localDemoVariable = "this is a local string variable" -- local to this function. Deleted as soon as procedure has completed
- --localDemoVariable = "this is also a global string variable" -- no local keyword: still available after procedure has completed
- print(localDemoVariable)
- end
- function main()
- luaScopeDemo()
- print(localDemoVariable) -- no longer available as was local to the procedure, so nil is printed. Does NOT cause error as in C#/Python
- io.write("Enter to quit")
- io.read() -- stop console closing
- end
- main()
Add Comment
Please, Sign In to add comment