When you write out a for loop in javascript like so:
for (var i = 0; i < 10; i++) {
//code
}
is the variable "i" considered global or local? It's not in a function so I'm assuming it's global? Is it wrong then to add another for loop further down the page using the same iterator "i"? Should you name the variable something else?
If the code is in the global scope (i.e. not in a function), then the variable is global.
If you reuse the variable further down in the code, then just omit the var. Declaring the same variable again doesn't cause a problem, but it looks like you are not aware that the variable already exists.
Reusing variables can sometimes make the code harder to follow, but on the other hand in your case it helps to keep the number of global variables down.
Related
I am a beginner in Kotlin and going through for loop
Simple code sample:
for (i in 1..5) print(i)
Please can someone advise me why we do not specify the counter/iterator variable type "i" with the keyword var / val. Since "var /val" is the standard way to declare variables in Kotlin.
This is simply how the for loop syntax is designed. I cannot speak for the designers, but I believe that's a design decision to avoid unnecessary bloat, and maybe confusion.
You cannot use an existing variable as the loop variable. The loop variable is scoped to the loop, and shadows existing ones from outer scopes. So it's kind of implied that you're declaring a new variable here, even without a keyword (however I have to admit that the shadowing behaviour would be clearer if we had to write the val/var keyword here).
Also, the loop variable is actually a val inside the loop's body (it cannot be reassigned), but it can feel like a var because it changes for each loop turn and is technically declared outside the loop's body. In effect, it's like a new val declared in the loop's body with a new value for each loop iteration.
So your example code can be thought of as:
var temp = 1
while (temp <= 5) {
val i = temp
println(i)
temp++
}
That's probably why the designers decided to not put any keyword here: it's unnecessary, and both val and var would be confusing in their own way.
suppose, if a for loop is inside a function, and I declare a variable inside for loop, will that variable be global variable or local variable confined to that function in which the for loop is present?
For the most part, loops do not have their own scope, so the variable's scope will be the scope of wherever the for loop lives. With that in mind, if the for loop is within a function, it will have local scope. One exception would be using let x = something in Javascript. This would release the memory at the end of the loops iteration.
Your question depends on a lot of factors i.e. programming language and the way you are declaring or using a variable.
For example in js:-
var y = 5;
function foo() {
var x = 2;
z = 5;
}
var x here is a local variable i.e. it cannot be used anywhere other than in the function foo.
var y on the other hand can be used globally as it is declared in the global scope
var z is not declared but it has been used to assign a value to it, so in javascript such a variable is considered to be declared in the global scope. So, it can be used outside the function foo
I am confused as to why I am allowed to do this (the if statement is to just show scope):
int i = 0;
if(true)
{
float i = 1.1;
}
I have a c# background and something like this is not allowed. Basically, the programmer is redeclaring the variable 'i', thus giving 'i' a new meaning. Any insight would be appreciated.
Thanks!
In C (and by extension, in Objective C) it is allowed to declare local variables in the inner scope that would hide variables of the outer scope. You can get rid of if and write this:
int i = 0;
{
// Here, the outer i becomes inaccessible
float i = 1.1;
{
int i = 2;
printf("%d", i); // 2 is printed
}
}
demo
C# standard decided against that, probably because it has a high probability of being an error, but C/Objective C does not have a problem with it.
Turn on "Hidden local variables" in your build settings to get a warning.
You're partially correct, yes, it gives i a new meaning, but it's not redeclaring the variable. It's another variable. But since the identifier is the same, the current scope will "hide" the previous, so any use of i inside that block refers to the float.
You're not redefining i, so much as shadowing i. This only works when the i's are declared at different levels of scope. C# allows shadowing, but not for if statements / switch statements, while C/C++/Objective-C allow such shadowing.
After the inner i goes out of scope, the identifier i will again refer to the int version of i. So it's not changing what the original i refers to. Shadowing a variable is generally not something you want to do (unless you're careful, shadowing is likely a mistake, especially for beginners).
I am aware there are other similar topics but could not find an straight answer for my question.
Suppose you have a function such as:
function aFunction()
local aLuaTable = {}
if (something) then
aLuaTable = {}
end
end
For the aLuaTable variable inside the if statement, it is still local right?. Basically what I am asking is if I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program's life, how does this work exactly?.
Additionally I read this definition for Lua global variables:
Any variable not in a defined block is said to be in the global scope.
Anything in the global scope is accessible by all inner scopes.
What is it meant by not in a defined block?, my understanding is that if I "declare" a variable anywhere it will always be global is that not correct?.
Sorry if the questions are too simple, but coming from Java and objective-c, lua is very odd to me.
"Any variable not in a defined block is said to be in the global scope."
This is simply wrong, so your confusion is understandable. Looks like you got that from the user wiki. I just updated the page with the correction information:
Any variable that's not defined as local is global.
my understanding is that if I "declare" a variable anywhere it will always be global
If you don't define it as local, it will be global. However, if you then create a local with the same name, it will take precedence over the global (i.e. Lua "sees" locals first when trying to resolve a variable name). See the example at the bottom of this post.
If I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program's life, how does this work exactly?
When your code is compiled, Lua tracks any local variables you define and knows which are available in a given scope. Whenever you read/write a variable, if there is a local in scope with that name, it's used. If there isn't, the read/write is translated (at compile time) into a table read/write (via the table _ENV).
local x = 10 -- stored in a VM register (a C array)
y = 20 -- translated to _ENV["y"] = 20
x = 20 -- writes to the VM register associated with x
y = 30 -- translated to _ENV["y"] = 30
print(x) -- reads from the VM register
print(y) -- translated to print(_ENV["y"])
Locals are lexically scoped. Everything else goes in _ENV.
x = 999
do -- create a new scope
local x = 2
print(x) -- uses the local x, so we print 2
x = 3 -- writing to the same local
print(_ENV.x) -- explicitly reference the global x our local x is hiding
end
print(x) -- 999
For the aLuaTable variable inside the if statement, it is still local right?
I don't understand how you're confused here; the rule is the exact same as it is for Java. The variable is still within scope, so therefore it continues to exist.
A local variable is the equivalent of defining a "stack" variable in Java. The variable exists within the block scope that defined it, and ceases to exist when that block ends.
Consider this Java code:
public static void main()
{
if(...)
{
int aVar = 5; //aVar exists.
if(...)
{
aVar = 10; //aVar continues to exist.
}
}
aVar = 20; //compile error: aVar stopped existing at the }
}
A "global" is simply any variable name that is not local. Consider the equivalent Lua code to the above:
function MyFuncName()
if(...) then
local aVar = 5 --aVar exists and is a local variable.
if(...) then
aVar = 10 --Since the most recent declaration of the symbol `aVar` in scope
--is a `local`, this use of `aVar` refers to the `local` defined above.
end
end
aVar = 20 --The previous `local aVar` is *not in scope*. That scope ended with
--the above `end`. Therefore, this `aVar` refers to the *global* aVar.
end
What in Java would be a compile error is perfectly valid Lua code, though it's probably not what you intended.
I work with scilab, but during a project, scilab has to deal with a large number of variables.
I was wondering if i can do the following
var_list = who_user();
for _var_ = var_list do
if _var_ is global then
writetofile(human_readablefile, _var_)
end
end
clear()
of course this is a pseudocode, and i have a few questions before i implement it.
I can not get var_list = who_user() working. so i believe the function does not return anything. I am reluctant to hack into the code of the "who_user" macro itself. Is there any other way to get the list of user variables in another variable?
Is there a way to find the global variables out of them?
If not, then what are some memory management techniques in scilab?
I am able to answer your first query:
From a slight modification of the who_user function itself:
function nams = who_user1()
//get user variables
[nams,mem]=who('get'); //get all variables
p=predef(); //number of system variable
st=stacksize()
nams=nams(1:$-p+1);mem=mem(1:$-p+1);
//modifiable system variables
excluded=['demolist','scicos_pal','%scicos_menu',..
'%scicos_short','%helps','%helps_modules','MSDOS','who_user','%scicos_display_mode', ...
'%scicos_help'];
ke=grep(nams,excluded)
nams(ke)=[];mem(ke)=[];
n=size(nams,1);
if n==0 then return,end
//format names on n*10 characters
ll=length(nams)+2;m=int((ll-1)/10)+1;
for k=1:max(m)
ks=find(m==k);
if ks<>[] then nams(ks)=part(nams(ks),1:(k*10));end
end
endfunction
This function should give you the list you desire (I have modified the name to who_user1).
You can find out whether a specific variable is global or not by using the isglobal() function, but you need to pass a variable to isglobal(), not the string that is the name of the variable. The function I've listed above returns a vector of strings.
An alternative approach you could try would be to rewrite the above function to return the variables (rather than their names) directly using varargout and then testing them for being globals.