This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Lua variables visibility and events management
#1
Hello.
I want to clear following programming points. Please read this, correct or confirm my understanding of script variables usage.

Default variable declaration in 'global'. Global variable has script file scope - it is visible for all blocks of script file and can be declared anywhere in script file (inside and outside function within script file). Global variable can't be used in other script files, and there is no possibility to declare it as 'extern' variable as it is possible in C language.
Local variable can be declared with 'local' keyword. Local variable can be declared inside function block and it is visible only in block where it is declared. 

If global and local variables with the same name are declared in the script only block where local variable is declared refers to local variable. All other parts of script code refers to global variable.

Event loads script every time when particular event occurs. And script is unloaded when script ends.
This means that all script variables are initialized when event starts script file and all variables are uninitialized when script end it's job. So if I want to create a counter to count number of events (for example) I can't to use global variable in the script because this variable will be initialized as nil each time when event will occurs.

But in this case I do not understand constructs like
Code:
require('luamodbus')

if not mbtcp then
  mbtcp = luamodbus.tcp()
end

'mbtcp' variable is nil each time when event script starts, so it is not necessary to check does this variable is initialized.

Does my reasoning is correct?
Reply


Messages In This Thread
Lua variables visibility and events management - by Andey - 18.11.2020, 11:14

Forum Jump: