Scripting Tutorial Part 1- Lua Basics

  • note: Lua syntax highlights dont work on code blocks indeed i used Js incase you notice difference


    Well as the title says this is a tutorial for those interrested to learn some of the basics of Multi Theft Auto resources & Lua language of course, as i saw that some topics discussed this subject on archives, Indeed you will be able to make a small script and why not a whole gamemode one day, So to make this accelerated i will be dividing the lesson on two parts (two different topics), one to explain what you need to know about Lua (this one) and the other about mta that will be posted as fast as possible


    For this part of the tutorial you wont need much, just a Lua Compiler (version 5.1-5.3.5) and a brain. You can use an online Compiler(recommandations rextester or repl) or download it from their official website here

    Topic Index:

    1. What is Lua, Introduction
    2. The basic syntax (The basic form of a Lua Script)
    3. Variables
    4. Data Types
    5. Strings
    6. Loops
    7. Conditions
    8. Iterators
    9. Tables

    1- Lua Overview/Introduction:

    Lua is a a lightweight (designed to have a small amount of memory footprint which is the amount of memory (RAM) a program is supposed to use), embedded (can be used/turned into an application mean its interpreter has an API (application program interface)) and multi-paradigmes (paradigmes are a way used to define/classify a programming languages it contains more details that you can shearsh for later to understand more) programming language, found the 1993 by some Brazilian progammer, finally the meaning of the word Lua means the moon in Portuguese dont confuse with other acronyms such as LUA.

    2- Basic Syntax:

    When it comes to Lua Syntax we shall talk in first place about 6 terms
    Sensitivity : upper case and low case count in Lua, indeed 'if' is not the same as 'If' or 'Name' is not the same as 'name'
    Identifiers: they are the words used to identify objects, variables or any defined/undefined element, identifiers are case sensitive as mentionned above and they consist of digits/underscore/letters and starting them with a number will return an error.

    --Working Identifiers 
    [name, _name, number_two] 
    --Wrong Identifiers 

    Comments: The use of comments is frequent in the word of programming, to define its every line that get ignored while reading the code (compiling) they can be presented by -- for 1 line comment or --[[--]] for multiple lines.

    Tokens: Tokens are what the Lua language is consisted of, they are the keywords,symbols, identifiers and variables

    -- in the following example i used 3 tokens 
    print('Hello World!')
    -- To show them
    'Hello World!'

    Whitespaces / empty lines: in Lua an empty line or a white space is just nothing and ignored when the code is started on contrast of different languages like python that Interacts with spaces.
    Keywords: they are tokens used for a purpose and cant be used as variables or identifiers

    --example : will return an error
    if = 'hello' 

    ==> all the keywords :

    and \ break \ do \ else \ elseif \ end \ false \ for \ function \ if \ in \ local \ nil \ not \ or \ repeat \ return \ then \ true \ until \ while

    3- Variables

    Variables are names that refer to a data storage, indeed we assign values/data to a variable that our code can interact with.
    Variables can be divided into 2 types in Lua

    • Global Variables: they are the variables with a global scope means can be accessed along the whole argorithme/program and every variable in Lua is global if its not specified
    • Local Variables : Obviously with a local scope accesable only inside a block of code or a function and local variables in Lua can be defined using the local token

    To declare a variable in Lua you dont need to specify the type of data just type it.

    [[variable_type (nothing if global)]]	[[variable_name]] 
    --- Example
    a = 5
    local a = 5

    4- Data Types

    Lua doesn't have types for variables but types for data, so data types are the forms of data that can be assigned to variables to make our program interact.
    Lua is based of 8 data types 5 basic and 3 complexe but i will introduce just 6 upon this tutorial (5 basic and 1 complexe):

    • Nil : We can say that a nil data is the equivalent of none, it can be used to refer to a variable without any data. And its not 0 or ''
    Sample = nil
    • Strings : When we want to realky define it with a scientifically term it represents an array of charactersit can take characters/numbers anything and its represented with '' or "" and more to add about later
    number = '2018'
    name = "Ronseal" 
    • Numbers : Numeric data can be a float/integer and they can be calculated as it's their main reason indeed a number is not same as a number inside a string.
    --- Example
    year = 2019
    birthY = 2003
    birthYS = '2003'
    --- Correct
    age = year - birthY
    print(age) --- returns 16
    --- False
    age = year - birthYS --- Returns an error here as im substracting a string from a number
    • Boolean : Its True or False their main use is for conditions (if) or to inform a success or fail of a function in Mta scripting that we will discuss at a next episode.
    correct = true
    wrong = false
    • Function(s) : methods and a block of code that can be called/triggered to run at a specific time, it takes most of the time parameters. We can make a function like this function name (parameters) [[code]] endAnd we will discuss more about upon all the tutorial.
    function test(a, b)
    print (a + b)
    test(5,8) --- returns 13
    • Tables/Metables Tables are only data structure in Lua, they are not variables or values but objects and it can take any values inside except nil that we discussed at the begin, to represent a table we use {}
      And metatables are made to help interacting with tables and using some features we cant access normally and we set them using setmetatable(table,metatable)
    myT = {} 
    myMT = {} 
    --- Created a table and set a meta table for 

    5- Strings

    After explaining what is a string in global this phase is just to explain some of the methods and functionalities that can help you manipulating em

    • tostring(variable/data) : one of the most known methods and it converts variables into a string which can help alot in some functions that can read/take only strings while you have numbers or other types of data
    --- type() method is used to return the type of a data
    number = 50
    print(type(number)) --- returns number
    new = tostring(number)
    print(type(new)) --- returns string
    • string.lower(variable) : this method takes a string turns all the characters in a string to lower case (miniscule).

    • string.upper : same as the above but in an opposite way it turns all the characters inside a string to upper case (majuscule).

    name = 'filex'
    upper = string.upper(name)
    print(upper) --- returns FILEX
    lower = string.lower(upper)
    print(lower) --- returns FILEX
    • string.reverse : reverse a string characters, the example can explain more.
    name = 'saes:rpg'
    new = string.reverse(name)
    print(new) --- returns gpr:seas
    new1 = string.reverse(new)
    print(new1) --- returns saes:rpg
    • string.len(argument) : argument is the value to add i added it this time to show that as we spoke about functions before, the important is that method returns the number of characters in a string it can be helpful to limit the lenght of a string or in the indexing.

    • string.sub(string, start_index, end_index_optional) : speaking about indexing this function returns a string after substracting a part of it based on a specified index. (RETURNS THE INTERVAL OF THE INDEX)

    • string.gsub(string, pattern, replacement, limit_int) : this method is used to replace a part of the string specified (pattern) with a replacement and this replacement can be limited if their is more than 1 pattern with same form.

    main = 'SAES is a great server'
    print(string.len(main)) --- returns 22 (18 characters and 4 spaces) 
    print(string.sub(main,1,4)) --- returns SAES
    print(string.gsub(main,' ', '_', 3)) --- returns SAES_is_a_great server by replacing 3 spaces with _
    print(string.gsub(main,'a great server', '15 year old')) --- returns SAES is 15 year old
    • .. (two points) : this may look useless but it can save you from a big pain in the ass when you want to attack too string it works like the operator + in other languages line python or js that im familiar with to explain more here's an example.
    P1 = 'SA' 
    P2 = 'ES' 
    print (P1..P2) --- returns SAES

    For me these are the most important to start with until mainting and you can find more after here strint.find() or string.format() and more. Finally the last thing to speak about in strings are escape sequences and because im lazy to explain something too easy to understand i will just pick up an already made one.
    To explain they are used to help us interpret or manipulate strings or add some characters that can turn it into errors like '' inside a string declared with '' aswell to use them we have '\'.
    alt text

    6- Loops

    This is an image i made to overview loops in general.
    alt text
    There is 4 types of loops in Lua in general, what does a loop mean, sometimes we need to provide a complexe way of execution for our programs and code a loop provides this feature as it help you to repeat a code many times, mainly in Lua we have :

    • While loop : while a condition is true it keeps repeating the code given
    age = 1
    year = 2003
    print('He lived') 
    while (age < 19) do
    print (year) 
    age = age + 1
    year = year + 1
    print('until he became 18')
    --- returns all years until 2020
    • for loop : allows you to repeat a statement a number of time under this property

    for init,max/min value, increment

    • init is a number you choose and will be the base of the condition the for loop make each time
    • min/max : its min if its smaller than the main init or max if its bigger and the for loop stops when the knit and max/min are equal
    • increment is the number the for loop adds each time to the init until it becomes equal to the min/max.
      To explain more heres an example
    for 10,20,5 do 
    print('hello') --- will return hello 3 times as it needed 5 two times to reach 20*+ first execution 
    for 10,4,-2 do
    print('hello') --- will return hello 4 times
    • repeat loop: a too simple loop repeats a statement until a condition is up


    a = 0
    a = a + 1
    until(a =5)
    --- returns SAES 5 times
    • Nested loops : its the use of one of the 3 loops together in one block code which is too simple.

    • Infinite loop : most of the time used to fire up your cpu but the infinite loop is the loom that keeps repeating the statement until the program is shut down

    while (true) do 

    7- Conditions

    Conditions are an efficient way in programming to plan your code and make it work properly Indeed.

    a = 10 
    if (a>5) then
    ---returns helll
    • In the following example we can notice the first example of conditions, in Lua to express a condition block we use the keyword if then set the condition if the condition is true (which is obvious in our example) the code will continue to work otherwise it will stop.
    a = 10 
    if (a>5) then
    • That's the same previous example but with a small addition you can notice, else that keyword helps to add another statement to work incase the if condition returns false otherwise it will be just ignored.
    a = 10 
    if (a>5) then
    elseif (a<5) then 
    • that was the same first example but i added elseif that keyword enables us to check another condition incase the first condition doesn't work

    alt text

    8- Iterators

    Gangs = {'ThC', 'AA', 'Cripz', 'Rebels' }
    for key, value in ipairs(Gangs) do
        print(key, value)
    --[[returns :
    1 ThC
    2 AA
    3 Cripz
    4 Rebels

    Each element inside a table is reffered to a key/index if its not defined its an int based on the position inside a table, indeed by noticing this example we can understand that this form of code can help us to fetch into tables and get the values and the keys of these values, we call this a generic 'For' Iterator.

    for k,v in pairs/ipairs(table) do

    • As i already mentionned k is the key indexed inside the table and v is the value attached to that index
    • pair/ipair : when its indexed by just numbers randomly we use ipairs but when a value is declared to a different index ipairs wont work and we need pairs
    --- Example of a table we need pair for
    names = {father = 'harold', son = 'richard', 54} 

    The other type of iterators is stateless/stateful iterators but they are a bit complex for now and i personally not experienced at em.

    9- Tables

    Same for strings i will provide two useful or three useful methods to control tables

    • table.insert(table, [pos,] value) : we can insert a value inside a table using this method and the position is an optional argument indeed if you leave it the value will be set at the end of the table
    Mtable = {1,2,3,4}
    for k, v in ipairs(Mtable) do
    print (v)
    • table.remove(table [, pos]) : removes an element from a table based on its position and if no position is specified the last element gets removed this method makes the table update from size, indexes after using it and its usage go just for numeric tables (with numbers as indexes)
    Mtable = {1,2,3,4}
    for k, v in ipairs(Mtable) do
    print (v)

    For more methods to manipulate your tables you can check the official lua library here

  • I tried to make it as summarized as possible and for experienced people if you notice any mistakes or problems please reply so.
    Otherwise for beginners if you have any question post it below too the mta part coming soon...

  • oO

  • In the loops, shouldnt it be:
    a = 0
    a = a + 1
    until (a = 5)

  • @Bidrift said in Scripting Tutorial Part 1- Lua Basics:

    In the loops, shouldnt it be:
    a = 0
    a = a + 1
    until (a = 5)

    Correct seems like my student is correcting me now 😂

  • BUMP

  • @Filex episode 2 please