summaryrefslogtreecommitdiffhomepage
path: root/tests/custom/00_syntax/14_array_literals
blob: 8651512046edb6c0df76dc0a607e8e60dac7a3c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
The ucode script language supports declaring arrays using JSON notation.

-- Expect stdout --
[ ]
[ "first", "second", 123, [ "a", "nested", "array" ], { "a": "nested object" } ]
-- End --

-- Testcase --
{%
	// An empty array can be declared using a pair of square brackets
	empty_array = [ ];

	// JSON notation is used to declare an array with contents
	json_array = [
		"first",
		"second",
		123,
		[ "a", "nested", "array" ],
		{ a: "nested object" }
	];

	// Printing (or stringifying) arrays will return their JSON representation
	print(empty_array, "\n");
	print(json_array, "\n");
-- End --


Additionally, ucode implements ES6-like spread operators to allow shallow copying
of array values into other arrays.

-- Expect stdout --
[ 1, 2, 3 ]
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3, 4, 5, 6, false, true ]
[ 1, 2, 3, false, true, 4, 5, 6 ]
[ 1, 2, 3, [ 4, 5, 6 ] ]
-- End --

-- Testcase --
{%
	a1 = [ 1, 2, 3 ];
	a2 = [ 4, 5, 6 ];

	print(join("\n", [
		// copying one array into another
		[ ...a1 ],

		// combining two arrays
		[ ...a1, ...a2 ],

		// copying array and append values
		[ ...a1, ...a2, false, true ],

		// copy array and interleave values
		[ ...a1, false, true, ...a2 ],

		// nested spread operators
		[ ...a1, [ ...a2 ] ]
	]), "\n");
%}
-- End --

Contrary to merging arrays into objects, objects cannot be merged into arrays.

-- Expect stderr --
Type error: ({ "foo": true, "bar": false }) is not iterable
In line 5, byte 21:

 `    print([ ...arr, ...obj ], "\n");`
  Near here -------------^


-- End --

-- Testcase --
{%
	arr = [ 1, 2, 3 ];
	obj = { foo: true, bar: false };

	print([ ...arr, ...obj ], "\n");
%}
-- End --