Forum

> > CS2D > Scripts > Bizarre error
Forums overviewCS2D overview Scripts overviewLog in to reply

English Bizarre error

2 replies
To the start Previous 1 Next To the start

old Bizarre error

EngiN33R
Moderator Off Offline

Quote
Okay, so this problem is solved, but I just wanted to share it here, because I don't exactly understand the nature of it. Some may call it a silly question because the answer is obvious, but I for one don't understand. Look:

1
2
3
4
5
6
7
8
9
function array(size,value) 
	local array = {}
	for i = 1, size do
		array[i]=value
	end
	return array
end

t=array(32,array(9,0))

Then, if
1
2
3
t[1][1]=1
print(t[1][1]) --> 1
print(t[2][1]) --> 1

And so on until t[9][1]. But, if it's done like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
t={{}}

for i=1,32 do
	t[i]={}
	for ii=1,9 do
		t[i][ii]=0
	end
end

t[1][1]=0

print(t[1][1]) --> 1
print(t[2][1]) --> 0

How come?

old Re: Bizarre error

Flacko
User Off Offline

Quote
Lua tables are passed by reference. This means that the values don't 'duplicate'
You just created a single table of size 9 and t is a table with 32 indices all pointing to the same table of size 9.
It's equivalent to:
1
2
nine = array(0,9)
t = array(32, nine)
Doing this makes the following statements true:
1
2
3
t[1] == t[2]
t[3] == nine
--etc
In short, any change you do to the nine table is reflected in all of t's indices.

This is how the table family of lua functions can operate directly on tables without needing to return a new one.

To create a multi dimensional table use the following functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
table.unpack = unpack

function table.copy(t)
	local b = {}
	for k,v in pairs(t) do
		if type(v)=='table' then
			v = table.copy(v)
		end
		b[k] = v
	end
	return b
end

function table.array(v, ...)
	local t = {}
	if arg[2] then
		v = table.array(v,table.unpack(arg,2))
	end
	for i=1,arg[1] do
		if arg[2] then v = table.copy(v) end
		t[i]=v
	end
	return t
end
This makes it easier to implment what you intended:
1
t = table.array(0,32,9)
The function table.copy returns a whole new table with the same keys and values from it's parameter which does the trick
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview