Forum

> > CS2D > Scripts > Array differences {}
Forums overviewCS2D overview Scripts overviewLog in to reply

English Array differences {}

4 replies
To the start Previous 1 Next To the start

old Array differences {}

Elev3n
User Off Offline

Quote
Hey comrades!
Can you tell me what the difference between these two 'arrays:

1
2
3
4
5
6
7
---------------------------------
--  ARRAY EXAMPLE 1  --
---------------------------------
example = {}
for i = 1, 32 do
     example[i] = 0
end

And:

1
2
3
4
5
6
7
8
9
10
---------------------------------
-- ARRAY EXAMPLE 2  --
---------------------------------
function initArray(m)
	local array = {}
	for i = 1, m do
		array[i]=0
	end
	return array
end

old Re: Array differences {}

useigor
User Off Offline

Quote
Second is function that lets you create array like first:
1
example = initArray(32)
It takes less space, when you create many arrays with same structure.

old Re: Array differences {}

Rainoth
Moderator Off Offline

Quote
First one creates a table and assigns 0 for it's keys from 1 to 32.
Second one creates a table and assigns 0 for it's keys from 1 to any number you definite (m).
Essentially, with second one you can create many tables with different lengths (lengths are unending but lengths as in keys that have "0" stored) whereas with first one you create a single table and assign 0s to 32 of it's keys.

Number 1 is shorter and more simple, perfect if you need one table.
Number 2 is better if you're planning to create many tables.

I personally don't use either

old Re: Array differences {}

VADemon
User Off Offline

Quote
user Rainoth doesn't use these array functions for a good reason. When you need to save values for particular players, it's better to create variables when a player joins or performs an action.
Example:
1
2
3
4
5
6
7
8
9
playerIP_list = {}

function join(id)
   playerIP_list[ id ] = player(id, "ip") -- creates variable inside this array
end

function leave(id)
   playerIP_list[ id ] = nil -- explicitely clears the variable, as you don't have any use for it
end
As opposed to using array functions:
1
2
3
4
5
6
7
playerIP_list = initArray(32) -- creates unecessary 32 values you won't ever use

function join(id)
    playerIP_list[ id ] = player(id, "ip") -- finally make use of 1 out of 32 variables from this array
end

-- usually there's no leave() function to clear a player's values. why? because stupid. this way the array always exists with 32 elements in it, utilizing RAM
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview