You have to explicitly declare your function a closure by adding closure
after the function arguments.
function Hi()
let a = "hi"
function s:inside() closure
echo a
endfunction
call s:inside()
endfunction
Without closure
, :call Hi()
will print out an error.
We use s:inside
to make the function script local, rather than global.
The dot concatenates strings: let str = "one thing" . "another"
.
let pos = match("one thing", "thing")
returns 4
, the point where thing
starts.
let str1 = str[0:pos]
splits the string from position 0 until 4 (as above). It returns one
.
With a string slice as above, you can use negative numbers, i.e. -1 means the end of the string.
function Hi()
let str = "one thing " . "another"
let pos = match(str, "thing")
let str = str[pos:-1]
echo str
endfunction
:call Hi()
will print thing another
.
getline()
can take two parameters: the start position in a file, and an end position in a file.
getline(1, '$')
will get all the lines from line 1 until the end. And it puts this in an array/list.
We can use the previously learnt filter()
function and regex operator to filter all the lines with a word in them:
let bicycles = getline(1, '$')->filter({ _,line -> line =~ '.*bicycle.*' })
Then you'd loop over this as normal.
You can use getline()
to get the current line as a string with getline(".")
or pass it a line number to get that line.
=~
matches strings with regular expressions.
You use single quotes so you don't need to double escape escape sequences like \s
etc.
function Hi()
if "hello" =~ 'hel.o'
echo "you said hello"
else
echo "you didn't say hello"
endif
endfunction
:call Hi()
will print you said hello
.
list_name->filter()
filters the list list_name
.
The filter function takes an inline function as a filter. The inline function syntax is { param1, param2 -> ... }
The filter function has the list index and value as parameters.
This example filters and gives you only the 2nd index of a list:
function Aa()
let alist = ["one", "two", "three"]
let alist = alist->filter({ i, line -> i == 1 })
echo alist
endfunction
:call Aa()
will output ["two"]
.