Got a question that the wiki doesn't answer? Ask on the forum (preferred), or join us on IRC.

BeastNode

CommandHelper/Staged/API/array get

From EngineHub.org Wiki
Jump to: navigation, search



Vital Info

Name array_get
Returns mixed
Usages array, index, [default]
Throws CastException

IndexOverflowException

Since 3.0.1
Restricted
No
Optimizations OPTIMIZE_CONSTANT

Description

Returns the element specified at the index of the array.

If the element doesn't exist, an exception is thrown. array_get(array, index). Note also that as of 3.1.2, you can use a more traditional method to access elements in an array: array[index] is the same as array_get(array, index), where array is a variable, or function that is an array. In fact, the compiler does some magic under the covers, and literally converts array[index] into array_get(array, index), so if there is a problem with your code, you will get an error message about a problem with the array_get function, even though you may not be using that function directly. If using the plain function access, then if a default is provided, the function will always return that value if the array otherwise doesn't have a value there. This is opposed to throwing an exception or returning null.

Usages

array_get(array, index, [default])

Examples (How do these work?)

Example 1

Demonstrates basic usage

Given the following code:

1   msg(array(0, 1, 2)[2]);


The output would be:

2

Example 2

Demonstrates exception

Given the following code:

1   msg(array()[1]);


The output would be:

(Throws IndexOverflowException: The element at index "1" does not exist)

Example 3

Demonstrates basic functional usage

Given the following code:

1   msg(array_get(array(1, 2, 3), 2));


The output would be:

3

Example 4

Demonstrates default (note that you cannot use the bracket syntax with this)

Given the following code:

1   msg(array_get(array(), 1, 'default'));


The output would be:

default


See Also

array_set, array, Learning Trail: Arrays



Navigation menu