Filex Posted February 15, 2019 Author Share Posted February 15, 2019 note: Lua syntax highlights dont work on code blocks indeed i used Js incase you notice differenceIntroductionWell 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 possibleRequirementsFor 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 hereTopic Index:What is Lua, IntroductionThe basic syntax (The basic form of a Lua Script)VariablesData TypesStringsLoopsConditionsIteratorsTables1- 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 termsSensitivity : 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 [5name] 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 themprint ('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 errorif = 'hello' ==> all the keywords :and \ break \ do \ else \ elseif \ end \ false \ for \ function \ if \ in \ local \ nil \ not \ or \ repeat \ return \ then \ true \ until \ while3- VariablesVariables 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 LuaGlobal 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 specifiedLocal 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 tokenTo declare a variable in Lua you dont need to specify the type of data just type it.[[variable_type (nothing if global)]] [[variable_name]] --- Examplea = 5local a = 54- Data TypesLua 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 = nilStrings : 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 laternumber = '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.--- Exampleyear = 2019birthY = 2003birthYS = '2003'--- Correctage = year - birthYprint(age) --- returns 16--- Falseage = year - birthYS --- Returns an error here as im substracting a string from a numberBoolean : 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 = truewrong = falseFunction(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)endtest(5,8) --- returns 13Tables/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 = {} setmetatable(myT,myMT)--- Created a table and set a meta table for 5- StringsAfter explaining what is a string in global this phase is just to explain some of the methods and functionalities that can help you manipulating emtostring(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 datanumber = 50print(type(number)) --- returns numbernew = tostring(number)print(type(new)) --- returns stringstring.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 FILEXlower = string.lower(upper)print(lower) --- returns FILEXstring.reverse : reverse a string characters, the example can explain more.name = 'saes:rpg'new = string.reverse(name)print(new) --- returns gpr:seasnew1 = string.reverse(new)print(new1) --- returns saes:rpgstring.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 SAESprint(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 SAESFor 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 '\'.6- LoopsThis is an image i made to overview loops in general.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 givenage = 1year = 2003print('He lived') while (age < 19) doprint (year) age = age + 1year = year + 1endprint('until he became 18')--- returns all years until 2020for loop : allows you to repeat a statement a number of time under this propertyfor init,max/min value, incrementdostatementendinit is a number you choose and will be the base of the condition the for loop make each timemin/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 equalincrement 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 examplefor 10,20,5 do print('hello') --- will return hello 3 times as it needed 5 two times to reach 20*+ first execution endfor 10,4,-2 doprint('hello') --- will return hello 4 timesendrepeat loop: a too simple loop repeats a statement until a condition is uprepeatstatementuntil(condition)a = 0repeat print('SAES')a = a + 1until(a =5)--- returns SAES 5 timesNested 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 downwhile (true) do print('SAES')end7- ConditionsConditions are an efficient way in programming to plan your code and make it work properly Indeed.a = 10 if (a>5) then print('hello') end---returns helllIn 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 print('hello') else print('goodbye') endThat'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 print('hello') elseif (a<5) then print('hi') endthat was the same first example but i added elseif that keyword enables us to check another condition incase the first condition doesn't work8- IteratorsGangs = {'ThC', 'AA', 'Cripz', 'Rebels' }for key, value in ipairs(Gangs) do print(key, value)end--[[returns :1 ThC2 AA3 Cripz4 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) dostatementendAs i already mentionned k is the key indexed inside the table and v is the value attached to that indexpair/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 fornames = {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- TablesSame for strings i will provide two useful or three useful methods to control tablestable.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 tableMtable = {1,2,3,4}table.insert(Mtable,5)for k, v in ipairs(Mtable) doprint (v)end--[[Returns:12345--]]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}table.remove(Mtable)for k, v in ipairs(Mtable) doprint (v)end--[[Returns:123--]]For more methods to manipulate your tables you can check the official lua library here Link to comment Share on other sites More sharing options...
Filex Posted February 15, 2019 Author Share Posted February 15, 2019 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... Link to comment Share on other sites More sharing options...
KARIM Posted February 15, 2019 Share Posted February 15, 2019 oO Link to comment Share on other sites More sharing options...
Yoda Posted February 15, 2019 Share Posted February 15, 2019 It belongs to therehttps://saesrpg.uk/category/30/scripting-and-development Link to comment Share on other sites More sharing options...
Bidrift Posted February 15, 2019 Share Posted February 15, 2019 In the loops, shouldnt it be:a = 0repeatprint("SAES")a = a + 1until (a = 5) Link to comment Share on other sites More sharing options...
Filex Posted February 15, 2019 Author Share Posted February 15, 2019 @Bidrift said in Scripting Tutorial Part 1- Lua Basics:In the loops, shouldnt it be:a = 0repeatprint("SAES")a = a + 1until (a = 5)Correct seems like my student is correcting me now Link to comment Share on other sites More sharing options...
Filex Posted June 9, 2019 Author Share Posted June 9, 2019 BUMP Link to comment Share on other sites More sharing options...
Liyones_ Posted June 14, 2020 Share Posted June 14, 2020 @Filex episode 2 please Link to comment Share on other sites More sharing options...
KiroSa Posted June 14, 2020 Share Posted June 14, 2020 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now