From 425c9ce4017f10f64aa22d7f5abf4ee089cd977a Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Tue, 5 Nov 2019 17:15:19 +0300 Subject: [PATCH] a special `last` variable in for loops (experimental) --- vlib/builtin/array_test.v | 14 ++++++++++++++ vlib/compiler/parser.v | 9 +++++++++ 2 files changed, 23 insertions(+) diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index cf632f1645..b551cfd785 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -479,3 +479,17 @@ fn test_eq() { assert [5,6,7].eq([6,7]) == false assert [`a`,`b`].eq([`a`,`b`]) == true } + +fn test_for_last() { + numbers := [1, 2, 3, 4] + mut s := '[' + for num in numbers { + s += '$num' + if !last { + s += ', ' + + } + } + s += ']' + assert s == '[1, 2, 3, 4]' +} diff --git a/vlib/compiler/parser.v b/vlib/compiler/parser.v index d2e651f65b..b514b217dc 100644 --- a/vlib/compiler/parser.v +++ b/vlib/compiler/parser.v @@ -3377,6 +3377,15 @@ fn (p mut Parser) for_st() { else if is_arr { typ = typ[6..]// all after `array_` p.gen_for_header(i, tmp, typ, val) + p.register_var(Var { + name: 'last' + typ: 'bool' + is_mut: false + is_used: true + }) + // TODO don't generate if it's not used. + // Otherwise it's a C warning + perf. + p.genln('bool last = $i == $tmp . len - 1;') } else if is_str { typ = 'byte'