- Thread starter
- #1
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
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:
Here are the Python 3 keywords for comparison:
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: --
Whereas in Python 3:
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:
Here is that same function written in Lua:
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?
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:
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:
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?
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:
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:
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:
Creating that same list in Python 3 and to print the values:
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:
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:
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:
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:
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:
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:
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:
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:
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/
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
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.
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 language | keyword | what it does | notes |
---|---|---|---|
lua | function | creates a function | uses "end" to end the function code block |
python 3 | def | creates a function | def is short for define |
lua | if | to create an if statement | uses "then" to end the statement, uses "end" to end the code block of the if statement |
python 3 | if | to create an if statement | uses ":" to end the statement, uses white space indentation to end the code block of the if statement |
lua | elseif | else if statement for use in if statements | uses "then" to end the statement |
python 3 | elif | else if statement for use in if statements | uses ":" to end the statement |
lua | nil | A type similar to null or undefined | |
python 3 | None | A type similar to null or undefined | |
python 3 | str | The 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:
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.TypeError: can only concatenate str (not "int") to str
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?
Note: changed i value to index in a[index] in the above due to the italics tag.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.
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: