• Welcome to Install Base!
    Join the Community and gain access to Prediction Leagues, Polls, specific answers and exclusive content now!

Learn badly with me, ggx2ac! - chapter 3: create tables using Lua (and Python comparison). Extra: Vim Tutorial and Exercise (and Markdown)

ggx2ac

Member
Scholar
(They publish Dark Souls)
Chapter 1: Learn badly with me, ggx2ac! - chapter 1: build a relational database using SQLite
Chapter 2: Learn badly with me, ggx2ac! - chapter 2: functional programming with lambda functions using Google Sheets (also works on Microsoft Excel)

This chapter will be easier to learn programming than in chapter 2. In chapter 2 I used JavaScript code to show how that looked compared to writing Lambda functions in Google Sheets/Microsoft Excel.

What is Lua?

Here's a 100 second video from the YouTube channel Fireship that introduces you to what Lua is:



Here is the official website for Lua: https://lua.org/

If the lua website is down due to maintenance, they have a mirror of the website here: https://www.tecgraf.puc-rio.br/lua/mirror/home.html

From the reference manual, I am quoting half of the introduction: https://lua.org/manual/5.4/manual.html#1
Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.

Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode with a register-based virtual machine, and has automatic memory management with a generational garbage collection, making it ideal for configuration, scripting, and rapid prototyping.

Lua is implemented as a library, written in clean C, the common subset of standard C and C++. The Lua distribution includes a host program called lua, which uses the Lua library to offer a complete, standalone Lua interpreter, for interactive or batch use. Lua is intended to be used both as a powerful, lightweight, embeddable scripting language for any program that needs one, and as a powerful but lightweight and efficient stand-alone language.

How simple is Lua?

I will be making comparisons of Lua to Python in this thread since they are similar in style compared to the C family of programming languages such as C, C++, Java, JavaScript, C#, Go, etc.

However, I will be pointing out the differences in Python compared to Lua because while they look similar, they behave differently.

Lua has 21 keywords while Python 3 has 33 keywords. Here are the 21 keywords:
and break do else elseif end
false for function goto if in
local nil not or repeat return
then true until while

Here are the Python 3 keywords for comparison:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

We won't go over every keyword and any information you need to know you can find from the reference manual. Always use the reference manual that matches the version of Lua you are using. The one linked earlier is v5.4.

Comparing a function using Lua and Python

If you're writing Lua code and you want to add a comment, it's the same as making a comment in SQL, a double hypen: --
Code:
-- this is a comment

Whereas in Python 3:
Python:
# this is a comment

One significant difference between Lua and Python is that Lua doesn't make use of white space like Python does.

Let's write a simple function to show this. What is a function? A function is a block of code that takes an input, runs code inside the block and then returns an output.

Here's a simple function in Python 3:
Python:
def add_two_numbers(a,b):
    if a == None or b == None:
        return print("An input is of type None")
    elif type(a) is str or type(b) is str:
        return print("An str input is not of type Number")
    else:
        c = a + b
  
    return print(c)

# calling the function multiple times
add_two_numbers(None, 3)
add_two_numbers("2", 3)
add_two_numbers(2, 3)

# output
# An input is of type None
# An str input is not of type Number
# 5

Here is that same function written in Lua:
C:
function add_two_numbers(a,b)
    if a == nil or b == nil then
        return print("An input is of type nil")
    elseif type(a) == "string" or type(b) == "string" then
        return print("A string input is not of type number")
    else
        c = a + b
    end
  
    return print(c)
end
-- calling the function multiple times
add_two_numbers(nil, 3)
add_two_numbers("2", 3)
add_two_numbers(2, 3)

-- output
-- An input is of type nil
-- A string input is not of type number
-- 5

Please note, there isn't Lua syntax highlighting when using the Code tags in this post. So, instead I am using C syntax highlighting to provide some color to the text else all the text is white.

When you look at the python code and the lua code, they look structurally the same, what are the differences?
programming languagekeywordwhat it doesnotes
luafunctioncreates a functionuses "end" to end the function code block
python 3defcreates a functiondef is short for define
luaifto create an if statementuses "then" to end the statement, uses "end" to end the code block of the if statement
python 3ifto create an if statementuses ":" to end the statement, uses white space indentation to end the code block of the if statement
luaelseifelse if statement for use in if statementsuses "then" to end the statement
python 3elifelse if statement for use in if statementsuses ":" to end the statement
luanilA type similar to null or undefined
python 3NoneA type similar to null or undefined
python 3strThe string type

As you're reading through this one thing probably sticks out to you. Even though Python is considered a simple programming language to use, their keywords are not as simple, let's pretend you already know how to use JavaScript and you want to use Python, you decide to transfer your knowledge over and start coding, you're obviously going to be confused when you find out Python calls names its function keyword "def". The issue isn't that it's a different word, the issue is that the word is something with IMPLICIT meaning, what does def mean? You have to look it up to then find out it's the keyword to create a function but then you're also wondering what def is short for.

Elif also sticks out as another word with implicit meaning, if you didn't know it was short for "else if" then you wouldn't know what it means.

The next difference to point out is very significant and is why some developers don't like Python. In Python, when you create a code block inside a def function, you must use white space indentation, when you need to nest a function inside a code block you must indent even further. To end the block you then go back outward in the indentation.

Now, look at these two blocks of Python 3 code:
Python:
def add_two_numbers(a,b):
    if a == None or b == None:
        return print("An input is of type None")
    elif type(a) is str or type(b) is str:
        return print("An str input is not of type Number")
    else:
        c = a + b
  
    return print(c)
Python:
def add_two_numbers(a,b):
    if a == None or b == None:
        return print("An input is of type None")
    elif type(a) is str or type(b) is str:
        return print("An str input is not of type Number")
    else:
        c = a + b

        return print(c)

What is the difference?
- In the first block of code at the else statement, you are creating a variable called "c". After the end of the If statement code block, the interpreter goes down the function and reads the return print(c) statement.

- In the second block of code at the else statement, you are creating a variable called "c", then you end the else statement with print(c). The interpreter finishes reading the function code block.

What is the problem with these two code blocks? They both produce the same output.
That means they work? Yes.
Why is it a problem? They both produce the same output.
And why is that a problem?

Let's pretend you have a very big python project with many def blocks in it and you are currently maintaining the code or adding something new. Somewhere during the hours of work you run the code and something goes wrong, the problem is that you can't figure out what is causing the bug because an error is not occurring.

If you accidentally press the TAB key on a line of code containing a return statement, it can completely change how your def code block works, and the problem is that you won't have noticed the change unless you're keeping track of things on a repository like github.

This is why I prefer how lua works, it doesn't use white space indentation to run code and, because it doesn't use white space indentation to determine where a code block is, you can use something so much more simpler to determine where the end of a code block is, the "end" keyword. If I tabbed the end keyword, it won't change how the function works.

In comparison to the C languages, you know where the beginning and end of a code block is by using these: { }.

Lua Values and Types

Lua has eight basic types: nil, boolean, number, string, function, userdata, thread, and table. More details here: https://lua.org/manual/5.4/manual.html#2.1

Lua makes use of Coercions and Conversions: https://lua.org/manual/5.4/manual.html#3.4.3

For example, it will convert "2" into 2 (changes from string to number) if you are doing something like "2" + 2, it will return 4.0 as a number type. If I remember correctly, this is an example of a weakly typed language.

Whereas in Python which is strongly typed, if you try to do "2" + 2, it will tell you:
TypeError: can only concatenate str (not "int") to str
which means it will not convert the number for you automatically. You would need to use a built-in function to convert the string to a number first.

A reminder that if you use JavaScript which is also weakly typed, this is the conversion it will do to "2" + 2, it will return "22" as a string type.

Lua, Python and JavaScript are all dynamic programming languages, meaning that you don't need to declare a type when you are creating a variable name. The interpreter figures it out.

Back to the Lua types, what is a table?
The type table implements associative arrays, that is, arrays that can have as indices not only numbers, but any Lua value except nil and NaN. (Not a Number is a special floating-point value used by the IEEE 754 standard to represent undefined numerical results, such as 0/0.) Tables can be heterogeneous; that is, they can contain values of all types (except nil). Any key associated to the value nil is not considered part of the table. Conversely, any key that is not part of a table has an associated value nil.

Tables are the sole data-structuring mechanism in Lua; they can be used to represent ordinary arrays, lists, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"]. There are several convenient ways to create tables in Lua (see §3.4.9).

Like indices, the values of table fields can be of any type. In particular, because functions are first-class values, table fields can contain functions. Thus tables can also carry methods (see §3.4.11).

The indexing of tables follows the definition of raw equality in the language. The expressions a[index] and a[j] denote the same table element if and only if index and j are raw equal (that is, equal without metamethods). In particular, floats with integral values are equal to their respective integers (e.g., 1.0 == 1). To avoid ambiguities, any float used as a key that is equal to an integer is converted to that integer. For instance, if you write a[2.0] = true, the actual key inserted into the table will be the integer 2.

Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.
Note: changed i value to index in a[index] in the above due to the italics tag.

Instead of explaining what each thing in the quote means, let's get to creating a table.

Creating a table

The Lua website provides an online book called "Programming in Lua" for free, however, the free book they provide covers only up to Lua 5.0, any new features are in later editions of the book which you have to purchase.

The free book is enough to learn how to create a table, the link to the book is here: https://www.lua.org/pil/1.html

The contents list is here, there are 29 chapters: https://www.lua.org/pil/contents.html#1

Pages to highlight:
- Some Lexical Conventions: https://www.lua.org/pil/1.3.html
- Tables: https://www.lua.org/pil/2.5.html
- Concatenation: https://www.lua.org/pil/3.4.html
- Stateless Iterators: https://www.lua.org/pil/7.3.html
- Arrays: https://www.lua.org/pil/11.1.html
- Array Size: https://www.lua.org/pil/19.1.html

From the reference manual:
- Table manipulation: https://lua.org/manual/5.4/manual.html#6.6
- Length operator: https://lua.org/manual/5.4/manual.html#3.4.7

Now this is the part where you can start coding something. Whenever you want to learn a new programming language, the provider of that programming language usually has a "playground" where you can code something online without having to install their language.

It's easier to have you start by using that playground than to be figuring out how to install the binaries for Lua, adding the env path on Windows if you use that, and then suggesting an IDE if you don't want to use the terminal.

One advantage that Python does have in comparison is that you can go to the Windows Store to download the official app and that will install the version of Python it contains along with its terminal. Much simpler and because it's on the Windows Store and from the creator of the language, you don't have to worry about whether it's safe to install.

I'm noting this for Windows users because in regard to Lua:
If you use Linux or macOS, Lua is either already installed on your system or there is a Lua package for it. Make sure you get the latest release of Lua (currently 5.4.6).

Go to this page and Lua will provide a list of playground sites: https://lua.org/demo.html

I am using the OneCompiler playground for this thread: https://onecompiler.com/lua/

Go to the OneCompiler link, the first thing you will see is blinding white light. Click on sun/moon icon which is next to the search icon at the top of the screen to activate Dark mode.

You will see three boxes on the page, the one on left side is where you will code, the boxes on the right side are the STDIN and Output. You won't need to do anything in the STDIN box for this.

The coding box already has print("Hello, World!") written for you. You should see a RUN button on the right side of the screen above the STDIN box, click the run button and the Output box will have Hello, World! printed.

Let's remove the code already written.

To create a table, create a variable and assign the table like below:
C:
a = {} -- {} indicates that the table is empty

If you do print(a) on the next line and run the code, the output will be nothing.

Because a Table is the sole data-structuring mechanism in Lua, we will go over the different type of data structures you can make with a Table. I will also create the equivalent data structure in Python.

Creating a List

Using the Table from Lua to create a list and to print the values:
C:
a = {1, 2, 3}
print(a)

-- output
-- table: 0x562d32ba8670

Creating that same list in Python 3 and to print the values:
Python:
a = [1,2,3]
print(a)

# output
# [1, 2, 3]

Now you're probably wondering, the print statement in Lua didn't print the values in the list, it only printed the memory address.

To actually print the values in the list in Lua, this is what you do:
C:
a = {1, 2, 3}

for index, value in ipairs(a) do
  print("index: " .. index, "value: " .. value)
end

-- output
--
-- index: 1    value: 1
-- index: 2    value: 2
-- index: 3    value: 3

Don't run away yet, unfortunately they didn't make printing a list as easy as in Python. One method is to use a for loop, to print everything inside a Table. The for loop reads, "for the index and values in ipairs(variable name) do this code and end", there is also a pairs method, but I chose ipairs instead because the list has iterators, I already linked the page earlier in Stateless Iterators which explains what they do. Inside the print statement I used ".." which does concatenation, since Lua is weakly typed it automatically converts the numbers to string as I concatenate them.

Let's print the same kind of list in Python:
Python:
a = [1, 2, 3]
b = list(enumerate(a))
print(b)
for i in b:
    print("index, value: " + str(i))

# output
# [(0, 1), (1, 2), (2, 3)]
# index, value: (0, 1)
# index, value: (1, 2)
# index, value: (2, 3)

I used the built-in function enumerate to create a tuple list where each index contained the index of the value and the value. Inside the print statement, the + symbol is used for concatenation but because the language is strongly typed, we wrap the value in a str() built-in function to convert the number to string.

One significant difference you'll have noticed is that Lua starts the index from 1, there is no zero index like in Python or almost every other language. I cannot explain why the creators of Lua did that but I guess it's easier to know where to index is that you don't have to think "the tenth index is going to be 10-1 = [9] because of zero-indexing", compared to "the tenth index is just [10]".

Also, if you read the table manipulation document. There is an easier way to print a list in Lua:
C:
a = {1, 2, 3}

print(table.concat(a, "\n"))
  
-- output
-- 1
-- 2
-- 3

One of the standard libraries in Lua is called table, with table.concat, you can loop through a list and print out the values. The second argument is a separator, if you don't use it, it will print "123", "\n" is the newline command.

Creating an Object

An object is something that contains key, value pairs. An object can be put into a list for when you have many objects.

Creating an object from a table using Lua and print out the values:
Code:
title = {
  name = "Resident Evil 2",
  year = 1998,
  platforms = {"PlayStation", "Nintendo 64"}
}

for index, value in pairs(title) do
  print("key: " .. index, "value: " .. value)
end
-- output
-- lua5.3: Main.lua:20: attempt to concatenate a table value (local 'value')
-- stack traceback:
--    Main.lua:20: in main chunk
--    [C]: in ?

I reused the print function from earlier when printing lists, here, title is an object that contains values that are either string, number, or a list of strings (which is of the type table). The error that occurred is because of the list of strings, how do we print them? We put an if statement for what to do when printing a table inside a table:
C:
title = {
  name = "Resident Evil 2",
  year = 1998,
  platforms = {"PlayStation", "Nintendo 64"}
}

for index, value in pairs(title) do
  if type(value) == "table" then
    print("key: " .. index, "value: " .. table.concat(value, ", "))
  else
    print("key: " .. index, "value: " .. value)
  end
end

-- output
-- key: name    value: Resident Evil 2
-- key: year    value: 1998
-- key: platforms    value: PlayStation, Nintendo 64

You'll have noticed I didn't use the ipairs function in the for loop this time and instead the pairs function is used. That's because the keys are not numbers hence it is not a list that can be iterated.

Why use objects then? You can get the value you need from an object by accessing its key, see below:
C:
print(title.name)
print(title.year)
print(title.platforms[1])
print(title.platforms[2])
  
-- output
-- Resident Evil 2
-- 1998
-- PlayStation
-- Nintendo 64

You wouldn't know what an object contained if all the keys were numbers.

Let's do all of the above but in Python 3:
Python:
title = {
    "name": "Resident Evil 2",
    "year": 1998,
    "platforms": ["PlayStation", "Nintendo 64"]
}

print(title)
print(title["name"])
print(title["year"])
print(title["platforms"][0])
print(title["platforms"][1])

# output
# {'name': 'Resident Evil 2', 'year': 1998, 'platforms': ['PlayStation', 'Nintendo 64']}
# Resident Evil 2
# 1998
# PlayStation
# Nintendo 64

As you can see, it was so much easier printing everything from the title in Python, however you had to enter the keys differently to access them. Also notice how I didn't need to wrap my keys in "" marks when I created the object in Lua, but I had to for Python.

In Python, if you want to access the keys like in Lua, you have to create a class which would be something like this:
Python:
class Game:
    def __init__(self, name, year, platforms):
        self.name = name
        self.year = year
        self.platforms = platforms

title2 = Game("Resident Evil 2", 1998, ["PlayStation", "Nintendo 64"])

print(title2.name)
print(title2.year)
print(title2.platforms[0])
print(title2.platforms[1])

-- output
-- Resident Evil 2
-- 1998
-- PlayStation
-- Nintendo 64

The reason you'd want to write code like the above in Python is that with an IDE using an LSP for Python, it becomes easy entering the keys from an object since the IDE gives you a list of the keys right after you type the dot in the object name such as title2.

This thread went longer than I expected for creating two data types from a Table, there are still more data types you can create which you can check the reference manual or the programming in Lua book that was used for these examples.

You've seen the differences between Python and Lua, Python is still one of the most popular programming languages used especially due to data science.

What is Lua used for? If you saw that Lua in 100 seconds video already then you know that Roblox is built on Lua (and Roblox recently translated React v17 from JS to Lua) but, if you want to make a game there are other options besides Roblox.

There is a 2d game engine called LÖVE, website: https://love2d.org/
Hi there! LÖVE is an *awesome* framework you can use to make 2D games in Lua. It's free, open-source, and works on Windows, macOS, Linux, Android and iOS.

If you scroll down the page of that website, you'll notice that the game Balatro was developed using LÖVE.

There are also game engines that use Python however, another option is the 2D/3D game engine Godot because Godot not only lets you use C# to code, but it also has its own script called GDScript: https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/gdscript_basics.html
GDScript is a high-level, object-oriented, imperative, and gradually typed programming language built for Godot. It uses an indentation-based syntax similar to languages like Python. Its goal is to be optimized for and tightly integrated with Godot Engine, allowing great flexibility for content creation and integration.

GDScript is entirely independent from Python and is not based on it.

So, if you're only familiar with Python, you can learn GDScript to create games in the Godot engine.


If you wanted to actually install Lua on your Windows PC (after having used Lua in the online playground), here's a random YouTube video I found that had someone going through downloading and installing the binaries, etc. I would pick the latest version of Lua to install although I don't know what the differences are in the versions that made him want to pick an older version:




Also, Lua is used in Neovim to customise your configurations. What is Neovim? "hyperextensible Vim-based text editor": https://neovim.io/

What is Vim? Watch this Vim in 100 seconds video from Fireship:



Then you can watch the Neovim in 100 seconds from Fireship afterward:




Chapter end.
 
Last edited:
Vim Motions Tutorial and Exercise
It didn't make sense to post some vim videos and not have a way to try vim out (more specifically, Vim Motions).

Here is an online Vim editor where you can try Vim out without having to install anything: https://www.vimonlineeditor.com/

Note: Vim was made for QWERTY users, but it's still customizable, allowing you to remap keys or create new functions. For example, the common one given for VSCode users that are using the vim extension is to add the command jj while in Insert mode so that pressing j twice lets you exit Insert mode into Normal mode without having to reach for the Esc key to exit into Normal mode.

The online editor will have a default text file on there, press the : key, then the e key, then the space key, then type new and then press enter. That will get rid of all of the default text and have a new file in use.

Copy the following Vim Motions tutorial and exercise that I just wrote inside the quote and then go to the online Vim editor and click on the paste button:
Basic cursor navigation:

Move the cursor down with the j key.

Move the cursor up with the k key.

Move the cursor right with the l key.

Move the cursor left with the h key.

Modes:

Vim has a number of modes, you will enter Normal mode by default. Pay attention to the bottom of the editor as there is a line that will tell you if you are in insert mode/visual mode or other information.

Modes:
Normal mode - Do commands like copy, paste. Command: Esc key
Insert mode - Edit text. Command: i key
Visual mode - Select text. Command: v key
Visual Line mode - Select line. Command: V key
Visual Block mode - Select block. Command: Ctrl key and v key.

To enter insert mode, press the i key or the a key which affects where the cursor enters from the left or right of the cursor position.

To enter Normal mode, press the Esc key or press the Ctrl key and the c key.

Press the o key to enter insert mode and add a new line below the cursor's position.

Press the Esc key to enter Normal mode or, press the Ctrl key and the c key.

Press the O key to enter insert mode and add a new line above the cursor's position.

Press the Esc key to enter Normal mode or, press the Ctrl key and the c key.

Press the v key to enter Visual mode. Press the v key again to go back to Normal mode.

Press the V key to enter Visual Line mode. Press the V key again to go back to Normal mode or, press the v key to enter Visual mode and then press the v key again to go back to Normal mode.

More cursor navigation commands:

Press the H key to move the cursor to the highest line on the screen.

Press the M key to move the cursor to the middle line on the screen.

Press the L key to move the cursor to the lowest line on the screen.

Press gg (the g key twice) to move the cursor to the beginning of the file.

Press the G key to move the cursor to the end of the file.

Press 45G (the keys 4, 5, G) to move to line 45.

Press 55G (the keys 5, 5, G) to move to line 55.

Press 60gg(the keys 6, 0, g, g) to move to line 60.

Press '' (the ' key twice) to go to the position before the last line jump.

In normal mode, you can also go to line 60 by typing :60 and then the enter key to move to line 60 in normal mode

Moving the cursor in a line:

Press the $ key to move the cursor to the end of the line.

Press the 0 key (zero key) to move the cursor to the beginning of a line.

Press the ^ key to move to the first character at the beginning of a line.

Press the w key to move the cursor to the beginning of the next word.

Press the b key to move the cursor to the beginning of the current word. Pressing the b key again will move the cursor to the beginning of the previous word.

Press the e key to move the cursor to the end of the current word. Pressing the e key again will move the cursor to the end of the next word.

Press the W key to move the cursor to the beginning of the next word bypassing punctuation marks. Use here: It's time to_use the W key! Fin-ish.

Press the B key to move the cursor to the previous word bypassing punctuation marks. Use here: It's time to_use the B key! Fin-ish.

Press the E key to move the cursor to the end of the current word bypassing punctuation marks. Use here: It's time to_use the E key! Fin-ish.

Press the f key and then press a character key to move the cursor to the next occurrence of that character in a line. Use here: Go to the first h.

Press the t key and then press a character key to move the cursor just before the next occurrence of that character in a line. Use here: Go before the first h.

Press the , key to repeat the f or t key action but going backwards.

Press the ; key to repeat the f or t key action but going forwards.

Press the } key to move the cursor to the previous paragraph (or code block when editing code)

Press the { key to move the cursor to the next paragraph (or code block when editing code)

Press the % key when the cursor is on the next curly brace to jump to the line containing the other curly brace.

Curly brace code block: {
You can also press the % key on the curly brace below to go back up
}

The % key can also be used on these brackets: ( ), [ ].

Copy and Paste methods:

Press the y key and then the space key to "yank" (copy) the character the cursor is on and then press the p key to paste that yanked character after the current cursor position. Use here: I

Press yy (the y key twice) to yank the line the cursor is on, then press p to paste after the current cursor position.

Press y$ (the y key and then the $ key) to yank the from the current cursor position (use here:) to the end of the line. Then press p to paste after the current cursor position.

Press yw (the y key and then the w key) to yank a word the cursor is on to the end of the word. Then press p to paste after the current cursor position.

Delete methods:

Press dd (the d key twice) to delete the line the cursor is on.
Press p to paste the deleted line after the cursor.

press diw (d key, i key, w key) to delete a whole word the cursor is on. Use here: Word.
Press P to paste the word before the cursor position.

Press dw (the d key and the w key) to delete a word the cursor is on to the end of the word. Press p to paste the word after the current cursor position.

Press the D key to delete a line from where the cursor is positioned. Use here: Delete this part of the line.
Press p to paste the deleted line after the cursor.

Any of the above d or D key commands can be used with the c or C keys to delete and then enter into Insert mode.
To enter Normal mode, press the Esc key or, the Ctrl key and the c key.

Press the x key to delete a character from where the cursor is positioned. Use here: Delllete thiiis. Press p to paste the deleted character after the current cursor position.

Press the X key to delete the character before the cursor (it's like using the backspace key).
Press P to paste the deleted character BEFORE the current cursor position.

Press the s key, it will delete the character the cursor is on and enter into Insert Mode.
To enter Normal mode, press the Esc key or, the Ctrl key and the c key.

Press the S key and it will delete the line the cursor is on and enter into Insert Mode.
To enter Normal mode, press the Esc key or, the Ctrl key and the c key.

Undo and redo:

Press the u key to undo an action.

Press the Ctrl key and the r key to redo the last action that was undone.

Press the U key to restore the last changed line.

Repeat:

Press the . key to repeat the last command.

Replace and Join:

Press the r key to replace a character the cursor is on, then press a character key to replace that character. Use here: Fyx dhis.

press the J key to join the line below to the current one with a space between.
One space.

press gJ (g key, then the J key) to join the line below to the current one without spacing between.
No space.

Search and Replace:

Pay attention to the bottom of the editor when searching.

Press the / key and then enter a word to search for all instances of that word. Find the word: and . Then press the enter key. Then press the n key to repeat the search forwards. Press the N key to repeat the search backwards.

Press the ? key and then enter a word to search backwards for all instances of that word. Find the word: delete. Then press the enter key. Then press the n key to repeat the search backwards. Press the N key to repeat the search forwards.

Press :%s :) key, % key, s key), then press the / key, then type in a word you want to replace, then press the / key, then type in the new word, then press the / key, then press the g key. This will replace all instances of the old word with the new word in the file. For example type: :%s/press/PRESS/g

Press u to undo the last action.

Exercises!

Ex1:
Enter the combo on the following lines:
Combo: w xp w l ri w rt ee re (repeat)
Lines:
Go nad ftx dhis linK.
Go nad ftx dhis linK.
Go nad ftx dhis linK.

Ex2:
Enter the combo on the following lines:
Combo: vi" d p e (repeat)
Lines:
"https://www.nintendo.co.jp/ir/en/index.html"
"https://www.nintendo.co.jp/ir/en/index.html"
"https://www.nintendo.co.jp/ir/en/index.html"

Ex3:
Enter the combo on the following lines:
Combo: di( p w (repeat)
Lines:
(Remove the words)
(Remove the words)
(Remove the words)

Ex4:
Enter the numbered combo on the corresponding line:
Combo 1: w 5dw
Combo 2: w 3dw
Combo 3: w dw
Lines:
Delete 5 words on this line this
Delete 3 words on this line
Delete one word

Ex5:
Enter the combo on the following line: (Esc = escape key, space = space key)
Combo: 5i ultra space Esc


Ex6:
Enter the combo on the following line: (Esc = Escape key, Enter = Enter key, space = space key)
Combo: 5i - new line Enter Esc


Ex7:
Enter the combo at the beginning of the first line: (Esc = Escape key, space = space key, Ctrl+v = Ctrl and v key, Ctrl+v = Ctrl and v key)
Combo: Ctrl+v 4j I 0 space Esc gv g Ctrl+a
Line:
hit
hits
hits
hits
hits


I am putting here the solutions to the exercise.

Solutions:
Ex1:
Go and fix this line.
Go and fix this line.
Go and fix this line.

Ex2:

Ex3:
()Remove the words
()Remove the words
()Remove the words

Ex4:
Delete this
Delete this line
Delete word

Ex5:
ultra ultra ultra ultra ultra

Ex6:
- new line
- new line
- new line
- new line
- new line

Ex7:
1 hit
2 hits
3 hits
4 hits
5 hits

That is the end of the exercises.

Here is a one of many websites with a cheat sheet: https://vim.rtorr.com/

Here is one website with a list of Vim tips: https://vim.fandom.com/wiki/Category:VimTip
 
Last edited:
Markdown
What is Markdown?
It’s a plain text format for writing structured documents, based on formatting conventions from email and usenet.
Also:
Markdown is a simple way to format text that looks great on any device. It doesn’t do anything fancy like change the font size, color, or type — just the essentials, using keyboard symbols you already know.

That comes from the following website: https://commonmark.org/

What is CommonMark?
A strongly defined, highly compatible specification of Markdown

If you go to that link above, you can learn Markdown in 60 seconds. They also have a ten-minute interactive tutorial.

They have a playground so you can try out Markdown and convert it to HTML: https://spec.commonmark.org/dingus/

Why am I bringing up Markdown?
You've read this thread, maybe you liked how Vim Motions works but you're not planning to do any coding. That's okay, Vim is a text-editor, so it is possible to have other uses for Vim and that's where Markdown comes in.

You might be familiar with this abbreviation: WYSIWYG (What you see is what you get), it is associated with Word Processors such as Microsoft Word.

Let's pretend you don't like using Microsoft Word online, it is free to use but you need an account to use it.

You instead choose to use Vim, or NeoVim, or Vim via extensions in VSCode for example. You create a Markdown file which is .md and you start typing. What is different compared to a word processor is that you're not having to move your mouse to click buttons to change things on the text.

Here's a table to show what markdown allows you to do:
SyntaxExampleResultNotes
Italics: _ or *_some words_some wordsUse \ to escape syntax if wanting to write * or _, e.g. \* and \_
Bold: __ or ****word**wordYou need to use \ for every character to escape the syntax.
Paragraph: One line

Another line
One line

Another line

A paragraph is consecutive lines of text with one or more blank lines between them.
Line break: \One line\
Another line
One line
Another line
You can also create a line break by using two blank spaces at the end of a line.
Headings: # to ######## Chapter 1

Chapter 1​

# = h1
## = h2
etc. The more # used, the smaller the header. Space required after the syntax used
Blockquotes: >> quote
>
> quote
>> nested
Each line needs >, > needs to be used on blank lines if quote has blank lines. >> nested blockquote
Unordered list: * or + or -- point
  • point
Space required after the syntax used
Ordered list: Number followed by . or )1) one
2. two
1. one
2. two
Use \ to escape syntax e.g. 1\. or 2\)
Links: []()[text](https://www.installbaseforum.com/)textSee more details from the interactive tutorial linked earlier
Images: ![]()![alt text](image url)image appears here else the alt text if link fails
See more details from the interactive tutorial linked earlier
Code: ` or ````inline code`

```
block code
```

inline code

(Ignore the Code: header)
Code:
block
 code
See more details from the interactive tutorial linked earlier
Nested lists:- list
1. Nested ordered list
- Nested unordered list
Use the interactive tutorial to see
See more details from the interactive tutorial linked earlier
Horizontal rule: ___ or ***text
***
text



A lot of the syntax is very simple to type, I wouldn't use two spaces at the end of the line for a line break, I would rather use \ for a line break.

As you would have noticed, a lot of the ways you can format text is similar to what you can do in posts on this forum. The difference is you can type it out with a simple syntax compared to having to move your mouse to click buttons.

Not only that, but the syntax is also much easier to type compared to using BB code. Wrapping text with * marks is much easier than using tags. Some BB code is still useful such as the quote tags since it can contain the link to a post and who posted it.

If you looked at the commonmark website, there are a number of websites listed that implemented their own version of Markdown to provide other features such as having syntax to do strikethrough or creating tables.

If you have went to the commonmark playground mentioned earlier, its playground converts markdown to html. If you choose to convert markdown to html, you can actually use HTML tags in your markdown to get the features that might not be featured in the version of markdown you use.

In that commonmark playground, paste the following text:
<p style="color:red">Red</p>
You will see in the HTML output Red

You would have also noticed that not only can you use HTML, but you can also add inline styles in the HTML tags to make use of CSS.

One of the persons in the CommonMark group: John MacFarlane has a program called Pandoc: https://pandoc.org/

What it does:
If you need to convert files from one markup format into another, pandoc is your swiss-army knife.

So, if you're wanting to convert your markdown file to HTML or to other file formats you can check that website.

Lastly, if you were writing markdown in a text editor, you would notice that the text editor itself is not a WYSIWYG word processor meaning that you would not see the changes to text after applying some formatting to a word. In VSCode you can use a command to preview what a markdown file looks like when the text is formatted however, if you want the equivalent of a WYSIWYG word processor to see the changes immediately, there are some third-parties that have done either an extension in VSCode or made their own WYSIWYG word processor for markdown files.

The point is, there are people who prefer making documents in markdown on a text-editor compared to using a word processor because they can keep their hands on their keyboard instead of having to stop and reach the mouse to click a few buttons to do formatting. Word processors do have key shortcuts such as Ctrl+b to select bold however, you have probably experienced this many times on a word processor, you go to bold a word, you then go to a new line, you start typing, the text is also bold, now you need to go and undo the bold on that text. Compared to Markdown, you wouldn't have had that problem because the word you wanted to bold would have been wrapped in the ** or __ marks.

You can still use a word processor if you prefer it. If you have never used markdown files before, now you know how they can be used.
 
Back
Top Bottom