# Wiki

Clone wiki# Core / vec3

**Back to Beyond the Codea in-app reference**

## vec3() function

### Introduction

Codea's in-app reference documents most of the `vec3()`

function. The function returns a userdata value that is a vector in three dimensions.

### Returning a three dimensional vector

The `vec3()`

function is used to return a new three-dimensional vector value as in the following example:

```
v1 = vec3(x1, y1, z1) -- x1, y1, z1 contain numbers for the respective co-ordinates
```

If any co-ordinates are omitted, then they are assumed to be `0`

. For example:

```
print(vec3()) -- Outputs: (0.000000, 0.000000, 0.000000)
print(vec3(1)) -- Outputs: (1.000000, 0.000000, 0.000000)
print(vec3(1, 2)) -- Outputs: (1.000000, 2.000000, 0.000000)
```

### Setting and getting individual coordinates

Indexing can be used to set and get individual coordinates, either by ordinal number or by letter (x, y, z), as summarised in the table below:

Co-ordinate | Index scheme | Index scheme |
---|---|---|

First | `v1[1]` | `v1.x` or `v1["x"]` |

Second | `v1[2]` | `v1.y` or `v1["y"]` |

Third | `v1[3]` | `v1.z` or `v1["z"]` |

### Operators

The result of the `vec3()`

function supports the `-`

(uniary), `*`

, `/`

, `+`

, `-`

, and `==`

operators, where the second operand is a number value in the case of `*`

(multiplication by a scalar) and `/`

(division by a scalar).

### Functions

The result also supports `tostring()`

to produce nicely-formatted output. Consequently, `print()`

also generates nicely-formatted output.

The result of the `vec3()`

function supports the indexed functions `dot()`

, `cross()`

, `len()`

, `lenSqr()`

, `dist()`

, `distSqr()`

and `normalize()`

. For example:

```
v1 = vec3(1, -1, 3)
v2 = vec3(-2, 5, -3)
-- Calculate the dot (scalar) product of two vectors
d = v1.dot(v1, v2) -- This syntax is equivalent ...
d = v1:dot(v2) -- ... to this syntax, using Lua's colon notation.
-- Calculate the length (magnitude) of first vector
l = v1.len(v1) -- This syntax is equivalent ...
l = v1:len() -- ... to this syntax, using Lua's colon notation.
```

Updated