aboutsummaryrefslogtreecommitdiff
path: root/spec/inputs/test/named_varargs_spec.yue
blob: a5ab2b13a12329208e08d5dfe2be17cb81f06e8d (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
describe "named varargs", ->
	it "should store varargs in named table", ->
		f = (...t) ->
			assert.same t.n, 3
			assert.same t[1], 1
			assert.same t[2], 2
			assert.same t[3], 3

		f 1, 2, 3

	it "should handle string arguments", ->
		f = (...args) ->
			assert.same args.n, 3
			assert.same args[1], "a"
			assert.same args[2], "b"
			assert.same args[3], "c"

		f "a", "b", "c"

	it "should handle empty varargs", ->
		f = (...t) ->
			assert.same t.n, 0
			assert.same #t, 0

		f!

	it "should preserve nil values", ->
		f = (...args) ->
			assert.same args.n, 5
			assert.same args[1], 1
			assert.same args[2], nil
			assert.same args[3], 3
			assert.same args[4], nil
			assert.same args[5], 5

		f 1, nil, 3, nil, 5

	it "should work with loop", ->
		f = (...t) ->
			sum = 0
			for i = 1, t.n
				sum += t[i] if type(t[i]) == "number"
			sum

		result = f 1, 2, 3, 4, 5
		assert.same result, 15

	it "should handle mixed types", ->
		f = (...args) ->
			types = [type(args[i]) for i = 1, args.n]
			types

		result = f "string", 123, true, nil, {}
		assert.same result, {"string", "number", "boolean", "nil", "table"}

	it "should work with table access", ->
		f = (...t) ->
			first = t[1]
			last = t[t.n]
			{first, last}

		result = f 1, 2, 3, 4, 5
		assert.same result, {1, 5}

	it "should support select with named args", ->
		f = (...args) ->
			second = select 2, table.unpack args
			second

		result = f "a", "b", "c"
		assert.same result, "b"

	it "should work with pcall", ->
		f = (...t) ->
			success = true
			for i = 1, t.n
				if t[i] == nil
					success = false
			success

		result = f 1, nil, 3
		assert.is_false result

	it "should handle function results", ->
		g = -> 1, 2, 3
		f = (...t) ->
			t.n

		result = f g!
		assert.same result, 3

	it "should work with unpacking", ->
		f = (...args) ->
			{table.unpack args}

		result = f "a", "b", "c"
		assert.same result, {"a", "b", "c"}

	it "should support passing named varargs to another function", ->
		outer = (...t) ->
			inner (table.unpack t)

		inner = (a, b, c) ->
			{a, b, c}

		result = outer 1, 2, 3
		assert.same result, {1, 2, 3}

	it "should work with default parameter", ->
		f = (x = 10, ...t) ->
			x + t[1] or 0

		result = f 5, 15
		assert.same result, 20

	it "should handle single argument", ->
		f = (...t) ->
			{t.n, t[1]}

		result = f 42
		assert.same result, {1, 42}