First, in Lua
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
ii={}
for i=1,5 do
	table.insert(
			ii,function()
				msg(i)
			end
		)
end
ii[1]()
i="test"
ii[1]()
This Lua script prints 1 and 1 after the other.
Now in Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
var ii=new Array();
for (i=1;i<5;i++) {
	ii.push(
		function() {
			alert(i);
		}
	);
}
ii[0]();
i="test";
ii[0]();
</script>
This, however prints 5 then test.
I realize it is because 'i' was declared in a global scope. I have searched online on how to define variables in different states but returned empty.
I would like to have the same return values in Lua for this Javascript.
Can anyone help me with this issue?
Edit:
I not sure if javascript scopes exist, but this method does not use local variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/javascript">
var ii=new Array();
for (i=0;i<=5;i++) {
	ii[i]=function(value) {
		return function() {
			alert(value);
		}
}(i);
}
ii[0]();
i="test";
ii[0]();
</script>
The problem was not push, but rather because I was using i globally when calling ii().
edited 2×, last 31.03.12 01:43:13 am
[SOLVED] Javascript: Array Holding Functions Scope
1 
Offline