Scripting Introduction: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
No edit summary
(Added link to MTA:SA Developers: Mobile.)
(51 intermediate revisions by 25 users not shown)
Line 1: Line 1:
Resource neboli Zdroje jsou klíčovou součástí MTA. Zdroj(Resource) je v podstatě složka nebo soubor ZIP, který obsahuje kolekci souborů, meta soubor, který popisuje na serveru, jak má být zdroj načten, a jaké soubory obsahuje. Resource je jako program v operačním systému - je možné jej spustit a zastavit, a více resource může běžet najednou.
Resources are a key part of MTA. A resource is essentially a folder or zip file that contains a collection of files, plus a "meta" file that describes to the server how the resource should be loaded and what files it does contain. A resource can be seen as being partly equivalent to a program running in an operating system - it can be started and stopped, and multiple resources can run at once.


Všechno, co má co do činění s skriptování děje ve resourcích, co resource se definuje, zda je to gamemode, mapa nebo něco jiného. MTA přichází s prostředky, které můžete volitelně použít ve svých gamemodech, jako maplimits aby playings do hrací plochy nebo deathpickups vytvořit zbraň Kleště.
Everything that has to do with scripting happens in resources, what a resource does defines if it is a gamemode, a map, or anything else. MTA comes with resources that you can optionally use in your gamemodes, such as map limits to keep playings within a playing area or death-pickups to create weapon pickups.
{{Tip | Váš první krok k zahájení Lua skriptů by mělo být pomocí editoru Lua. To umožňuje skriptování mnohem jednodušší. Doporučujeme [http://notepad-plus.sourceforge.net/uk/site.htm Notepad + +] nebo [http://luaedit.sourceforge.net/ LuaEdit]. K dispozici je také neoficiální [[MTASE | MTA Script Editor]]. (V work-in-progress stavu), které si můžete vyzkoušet}}
{{tip|Your first step to begin Lua scripting should be using a Lua editor. This makes scripting much easier. We recommend [https://code.visualstudio.com/ Visual Studio Code], [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] or [https://www.sublimetext.com/ Sublime Text]. There is also an unofficial Android mobile app [[MTA:SA_Developers:_Mobile|MTA:SA Developers: Mobile]] that you can try out.}}


== Vytvoření pracovní skriptu ==
==Creating a working script==
Nejprve se dozvíte, jak vytvořit základní skript, který umožňuje hráč chodit po městě, krok za krokem.
We will first learn how to make a basic script that lets the player walk around in the city, step by step.
=== Kde jsou všechny skripty? ===
===Where are all the scripts?===
Pojďme se podívat na skript je strukturou souborů. Jděte do složky serveru MTA, a po cestě níže:
Let's take a look at the script's file structure. Go to your MTA Server folder, and follow the path below:


server / mods / deathmatch / resources /
server/mods/deathmatch/resources/


Uvidíte spoustu  .Zip souborů,nebo složek, které jsou balené ukázkové skripty dodávané s MTA. Každý soubor je "zdrojem", a budou všechny rozbaleny(pouze ZIP soubory) a načteny na serveru, když se server spustí. Chcete-li vytvořit svůj vlastní resource, prostě udělejte složku s jakýkoliv jménem(Bez mezer,teček, místo mezer použijte _ ).My použijeme "myserver" pro nyní.
You will see a lot of .zip files, which are the packaged sample scripts shipped with MTA. Each file is a "resource", and they will all be unzipped and loaded by the server when it starts. To create your own resource, simply make a folder with your preferred name. We'll use "myserver" for this tutorial.


Nyní byste měli být v tomto adresáři:
Now you should be under this directory:  


server / mods / deathmatch / resources / myserver /
server/mods/deathmatch/resources/myserver/


=== Identifikace zdroje ===
===Identifying your resource===
Aby server věděl,co obsahuje resource, musí meta.xml být vytvořen na seznamu obsahu resource(v resource). Musí být umístěn ve zdrojovém kořenovém adresáři, který je "myserver" složka v našem případě. Takže vytvořte textový soubor a pojmenujte jej "meta.xml", a otevřete jej v programu Poznámkový blok.
In order to let the server know what's in the resource, a ''meta.xml'' file must be created to list the resource's content. It must be located in the resource's root directory, which is the "myserver" folder in our case. So create a text file and name it "meta.xml", and open it with notepad.


Zadejte následující kódy v meta.xml souboru:
Enter the following codes in the ''meta.xml'' file:
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
<meta>
<meta>
     <info author="VaseJmeno" type="gamemode" name="My server" description="Můj první MTA server" />
    <info author="YourName" type="gamemode" name="My Server" description="My first MTA server" />
     <script src="script.lua" />
    <script src="script.lua" type="server" />
</meta>
</meta>
</ Code>
</syntaxhighlight>
V <Info /> tagu, je tu "type" pole, které označuje, že zdroj je typu 'gamemode', mohou být i typu mapy, které budou vysvětleny později. Gamemode je to, co budete potřebovat, aby se "rozjel" server.
In the ''<info />'' tag, there's a "type" field which indicates that the resource is a ''gamemode'' instead of a regular include or a ''map'', which will be explained later. A gamemode is what you need to make a stand-alone server.  


<script /> Tag určuje soubory skriptů obsažených v prostředku, které vytvoří další.
The ''<script />'' tag indicates the script files contained in the resource, which we will create next.
=== Vytváření jednoduchého skriptu ===
===Creating a simple script===
Všimněte si, že v <script /> tag výše Lua soubor není pod jiným adresářem. Proto budeme vytvářet soubor ve stejné složce jako meta.xml. Nyní můžete zkopírovat a vložit následující kód do script.lua:
Note that in the ''<script />'' tag above, the .lua file is not under another directory. Therefore we'll create the file in the same folder as meta.xml. Now you can copy and paste the following code into script.lua:
<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
local spawnX, spawnY, spawnZ = 1959,55, -1714.46, 10
local spawnX, spawnY, spawnZ = 1959.55, -1714.46, 10
function joinHandler ()
function joinHandler()
spawnPlayer (source, spawnX, spawnY, spawnZ)
spawnPlayer(source, spawnX, spawnY, spawnZ)
fadeCamera (source, true)
fadeCamera(source, true)
setCameraTarget (source, source)
setCameraTarget(source, source)
outputChatBox ("Vítejte na mém serveru", source)
outputChatBox("Welcome to My Server", source)
end
end
addEventHandler ("onPlayerJoin", getRootElement (), joinHandler)
addEventHandler("onPlayerJoin", getRootElement(), joinHandler)
</ Code>
</syntaxhighlight>
Skript vás spawne(vytvoří/narodí) na souřadnici (x, y, z) která uvedena výše, když se připojíte do hry. Všimněte si, že funkce fadeCamera musí být použita ,neboť by byla obrazovka černá. Také ve verzích po DP2, musíte nastavit pozici kamery (jinak by hráč viděl, jen modré nebe).
The script will spawn you at the coordinate (x, y, z) specified above when you join the game. Note that the ''fadeCamera'' function must be used or the screen will be black. Also, in releases after DP2, you need to set the camera target (otherwise all the players will see is the blue sky).


Source proměnná určuje, kdo spustil událost. Vzhledem k tomu,že hráč se připojil při spuštění kódu, můžete použít tuto proměnnou aby jste se podívali, kdo se připojil. Takže to bude spawnovat, že hráč namísto každého nebo náhodnou osobu.
The '''source''' variable indicates who triggered the event. Since a player has joined when the code is triggered, you use this variable to look which has joined. So it'll spawn that player instead of everyone or a random person.


Pokud bychom se blíže podívali na [[addEventHandler]], můžete vidět 3 věci(argumenty): "onPlayerJoin", což znamená, když je spuštěna hra(Při připojení hráče na server). getRootElement (), ukazuje o co / kdo to může být spuštěna. (GetRootElement () je všechno / všichni) A joinHandler, který indikuje funkci, která má být spuštěna po aktivaci události. Další podrobnosti budou vysvětleny později v jiném příkladu, teď pojďme ,stačí spustit server a zkuste to!
If we have a closer look on [[addEventHandler]], you can see 3 things: 'onPlayerJoin', which indicates when it's triggered. getRootElement(), which shows by what/who it can be triggered. (getRootElement() is everything/everyone) And joinHandler, which indicates the function that has to be triggered after the event is triggered. Other details will be explained later in another example, now let's just run the server and try it out!


=== Spuštění skriptu ===
===Running the script===
Chcete-li spusit server, stačí spustit spustitelný soubor v adresáři /server. Seznam serverů ve statistikách se vám ukážou jako první, poznamenejte si číslo portu, které budete potřebovat při vstupu do hry. Pak server načte všechny resource v rámci mods / deathmatch / resources / adresáře, a pak "připraven přijímat připojení!"
To get the server started, simply run the executable under the server/ directory. A list of server stats will be shown first; note the port number, which you'll need when joining the game. Then the server loads all the resources under the mods/deathmatch/resources/ directory, and then "ready to accept connections!"


Před připojením k serveru, musíte spustit gamemode. Napište "myserver" nebo "start myserver" a stiskněte klávesu Enter. Server spustí gamemode,který jste právě vytvořili, a také ukáže všechny chyby a varování. Nyní můžete spustit klienta MTA, a "Quick Connect" pomocí IP adresy vašeho serveru a číslo portu, který jste viděli dříve. Pokud vše půjde dobře, po několika sekundách se vaše postava bude chodit po ulicích Los Santos.
Before you connect to the server, you must run the gamemode. Type "start myserver" and press Enter. The server will start the gamemode you just created, and will also show any errors and warnings from this point on. Now you can start the MTA client, and "Quick Connect" using the IP address of your server and the port number you saw earlier. If all goes well, after a few seconds your character will be walking on the streets of Los Santos.


Další přidáme příkaz do skriptu, že hráči mohou použít, aby se vedle hráče vytvořilo vozidlo. Můžete přeskočit,na pokročilé skriptování s [[Map manager | Map Manager]], který pokračuje tento návod. Další odbočka z tohoto tutoriálu je [[Úvod do Skriptování GUI]], můžete sledovat,učit se, jak na Graphical User Interface v MTA(Grafické Uživatelské Rozhraní).
Next, we'll add a command to your script that players can use to spawn a vehicle beside their position. You may skip it and check out more advanced scripting with the [[Map manager|Map Manager]], which continues this tutorial. Another branch from this tutorial is [[Introduction to Scripting GUI]], you may follow it to see how the Graphical User Interface in MTA is drawn and scripted.


== Vytvoření jednoduchého příkazu ==
==Creating a simple command==
Pojďme zpět k obsahu script.lua souboru. Jak již bylo zmíněno výše, chceme nabídnout příkaz k vytvoření vozidlo vedle vaší aktuální polohy ve hře. Za prvé musíme vytvořit funkci chceme použít, a příkaz psovoda, který vytvoří příkaz hráč bude moci vstoupit do konzole.
Let's go back to the content of the ''script.lua'' file. As mentioned above, we want to provide a command to create a vehicle beside your current position in the game. Firstly we need to create a function we want to call and a command handler that creates the command the player will be able to enter in the console.


<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
- Vytvoření funkce, příkazu , s argumenty: thePlayer, příkaz, vehicleModel
-- create the function the command handler calls, with the arguments: thePlayer, command, vehicleModel
function createVehicleForPlayer(thePlayer, command, vehicleModel)
function createVehicleForPlayer(thePlayer, command, vehicleModel)
   - Vytvoří vozidlo a další věci
  -- create a vehicle and stuff
end
end


- Vytvoří příkaz
-- create a command handler
addCommandHandler ("createvehicle", createVehicleForPlayer)
addCommandHandler("createvehicle", createVehicleForPlayer)
</ Code>
</syntaxhighlight>
Poznámka: Funkce jména jsou v příkladech kódu na wiki a je spojena s dokumentací funkcí "''.
''Note: Function names are clickable in code examples on the wiki and linked to the functions' documentation.''


==== O příkazech ====
====About command handlers====
Prvním argumentem [[addCommandHandler]] je název příkazu,který bude moci hráč použít, druhý argument je funkce která se použije, v tomto případě createVehicleForPlayer.
The first argument of [[addCommandHandler]] is the name of the command the player will be able to enter, the second argument is the function this will call, in this case ''createVehicleForPlayer''.


Pokud jste již zkušení s skriptováním, budete vědět, že jste požili funkce, jako je tato:
If you have already experienced in scripting, you will know that you call a function like this:
<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
functionName (argument1, argument2, argument3, ..)
functionName(argument1, argument2, argument3, ..)
</ Code>
</syntaxhighlight>
<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
functionName (thePlayer, commandName, argument3, ..)
functionName(thePlayer, commandName, argument3, ..)
</ Code>
</syntaxhighlight>
Pokud bychom se blíže podívali na spodní příklad výše, můžeme vidět argument1 je thePlayer a argument2 commandName. thePlayer je prostě ten, kdo napsal příkaz, tak jak se tomu říká, bude proměnná obsahovat hráče, který aktivuje příkaz. commandName je prostě příkaz, který zadali. Takže v případě, že zadaný "/ pozdravit", bude tento argument obsahovat "pozdravil". Argument 3 je něco navíc,co zadal hráč, budete se učit trochu dále v tutoriálu. Nikdy nezapomeňte, že první 2 argumenty jsou standardní argumenty, ale můžete pojmenovat na cokoliv budete chtít.
If we have a closer look on the lower example above, we can see argument1 is thePlayer and argument2 the commandName. thePlayer is simply the one who typed the command, so whatever you call it, the variable will contain the player who activated the command. commandName is simply the command they typed. So if they typed "/greet", this argument will contain "greet". Argument 3 is something extra the player typed, you'll learn it a little bit further in the tutorial. Never forget that the first 2 arguments are standard arguments, but you can name them to anything you want.


My nazýváve [[addCommandHandler]] funkci tímto způsobem již od kroku'' createVehicleForPlayer'' je funkce příliš, může to být nazýván tímto způsobem také. Ale my se pomocí příkazového ovladače pro to, který volá jej v příbuznými způsoby, vnitřně.
We called the [[addCommandHandler]] function this way already and since ''createVehicleForPlayer'' is a function too, it can be called that way as well. But we are using a command handler for that, which calls it in a similar manner, internally.


Například: někdo zadá "createvehicle 468" ve hře vytvoří(spawne) Sanchez, příkaz handler volá createVehicleForPlayer funkci, jako, pokud budeme mít tento řádek kódu ve skriptu:
For example someone types "createvehicle 468" in-game in the console to spawn a Sanchez, the command handler calls the createVehicleForPlayer function, as '''if''' we would have this line of code in the script:
<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
createVehicleForPlayer (thePlayer, "createvehicle", "468") - thePlayer je hráč prvkem hráče, který použil příkaz
createVehicleForPlayer(thePlayer,"createvehicle","468") -- thePlayer is the player element of the player who entered the command
</ Code>
</syntaxhighlight>
Jak můžeme vidět, že poskytuje několik parametrů: hráč, který volal příkaz, příkaz vstoupil a co textu měl po tom, v tomto případě "468" vozidla jako ID pro Sanchez. První dva parametry jsou stejné jako u všech velitelských manipulátory, které si můžete přečíst na [[addEventHandler]] stránce. Pro tuto skutečnost, budete vždy definovat alespoň ty dva parametry použijete některý poté (například ke zpracování textu, který byl zadán po příkazu, jako v našem příkladu model vozidla id).
As we can see, it provides several parameters: the player who called the command, the command he entered, and whatever text he had after that, in this case, "468" as vehicle id for the Sanchez. The first two parameters are the same with all command handlers, which you can read on the [[addEventHandler]] page. For this fact, you always have to define at least those two parameters to use any after that (for example to process text that was entered after the command, like in our example the vehicle model id).


Poznámka: Musíte přidat příkaz poté, co jste definovali funkci manipulačního, jinak to nemůže najít. Pořadí exekučních věcech.
''Note: You have to add the command handler AFTER you defined the handler function, else it can't find it. The order of execution matters.''


==== Psaní funkci ====
====Writing the function====
Za účelem vyplnění funkci jsme vytvořili, musíme přemýšlet o tom, co máme dělat:
In order to fill the function we created, we need to think about what we have to do:
* Získejte hráčovu pozici, takže víme, kde se vytvoří vozidla (chceme aby se objevilo vedle hráče)
* Get the players position, so we know where to spawn the vehicle (we want it to appear right beside the player)
* Výpočet pozici chceme, aby vozidlo bylo vedle hráče(nechceme, aby bylo v hráči)
* Calculate the position we want to spawn the vehicle at (we don't want it to appear in the player)
* Vytvořit vozidlo
* Spawn the vehicle
* Zkontrolovat, zda byl spawn úspěšný, nebo neuspěšný
* Check if it has been spawned successfully, or output a message


Za účelem dosažení našich cílů, musíme použít několik funkcí. Chcete-li najít funkci, musíme použít, měli bychom navštívit [[Skriptovací funkce | Server Seznam funkcí]]. Nejprve potřebujeme funkci dostat hráčovu pozici. Protože hráči jsou prvky, nejprve přejdeme na'' 'Elementy funkcí''', kde najdeme [[getElementPosition]] funkci. Kliknutím na název funkce v seznamu, se dostanete na popis funkce. Tam vidíme syntaxi, co to udělá a obvykle příklad. Syntaxe nám ukazuje, jaké argumenty můžeme nebo musí být sepsány.
In order to achieve our goals, we have to use several functions. To find the function we need to use, we should visit the [[Scripting Functions|Server Functions List]]. First, we need a function to get the player's position. Since players are Elements, we first jump to the '''Element functions''' where we find the [[getElementPosition]] function. By clicking on the function name in the list, you get to the function description. There we can see the syntax, what it returns, and usually an example. The syntax shows us what arguments we can or have to submit.


Pro [[getElementPosition]], syntaxe je:
For [[getElementPosition]], the syntax is:
<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
float, float, float getElementPosition (element theElement)
float, float, float getElementPosition ( element theElement )
</ Code>
</syntaxhighlight>


Tři argumenty před názvem funkce jsou návratový typ. V tomto případě to znamená, že funkce vrátí tři argumenty s desetinnou čárkou čísla. (X, y a z) Uvnitř závorek, můžete vidět, jaké argumenty musíte předložit. V tomto případě pouze prvek, jehož pozici chcete dostat, což je hráč v našem příkladu.
The three ''float'' in front of the function name is the return type. In this case, it means the function returns three floating-point numbers. (x, y, and z) Within the parentheses, you can see what arguments you have to submit. In this case, only the element whose position you want to get, which is the player in our example.


<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
function createVehicleForPlayer (thePlayer, command, vehicleModel)
function createVehicleForPlayer(thePlayer, command, vehicleModel)
- Získá pozici x, y, z .
-- get the position and put it in the x,y,z variables
- (local znamená, proměnná existuje pouze v aktuálním rozsahu, v tomto případě, funkce)
-- (local means, the variables only exist in the current scope, in this case, the function)
local x, y, z = getElementPosition (thePlayer)
local x,y,z = getElementPosition(thePlayer)
end
end
</ Code>
</syntaxhighlight>


Další chceme zajistit, že vozidlo nebude spawnuto přímo v hráčovi, takže jsme přidali několik jednotek na x proměnnou, která bude dělat to, že přidá něco na východ od hráče.
Next, we want to ensure that the vehicle won't spawn directly in the player, so we add a few units to the ''x'' variable, which will make it spawn east from the player.


<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
function createVehicleForPlayer (thePlayer, command, vehicleModel)
function createVehicleForPlayer(thePlayer, command, vehicleModel)
local x, y, z = getElementPosition (thePlayer) - Získá pozici hráče
local x,y,z = getElementPosition(thePlayer) -- get the position of the player
x = x + 5 - Přidá 5 do polohy X
x = x + 5 -- add 5 units to the x position
end
end
</ Code>
</syntaxhighlight>


Nyní potřebujeme jinou funkci, jeden, aby se vytvořilo vozidlo. Jsme opět vyhledali ji na [[Skriptovací funkce | Server Seznam funkcí]], tentokrát - od hovoříme o vozidlech - v'' 'Vehicle funkcí''' sekce, kde budeme chtít [[createVehicle]] . V této funkci se syntaxí, máme pouze jednu návratový typ (což je častější), vozidlo prvek, který odkazuje na vozidle jsme právě vytvořili. Také vidíme, že některé argumenty jsou uzavřeny v [], což znamená, že jsou to volitelné.
Now we need another function, one to spawn a vehicle. We once again search for it on the [[Scripting Functions|Server Functions List]], this time - since we are talking about vehicles - in the '''Vehicle functions''' section, where we will choose [[createVehicle]]. In this function's syntax, we only have one return type (which is more common), a vehicle element that points to the vehicle we just created. Also, we see that some arguments are enclosed within [ ] which means that those are optional.


Máme již všechny argumenty, které potřebujeme pro [[createVehicle]] v naší funkce: poloha prostě počítá v'' X, Y, Z'' proměnných a modelu ID, které jsme poskytli prostřednictvím příkazu ("createvehicle 468") a přístup do funkce jako'''' vehicleModel proměnné.
We already have all arguments we need for [[createVehicle]] in our function: The position we just calculated in the ''x,y,z'' variables and the model id that we provided through the command ("createvehicle 468") and can access in the function as ''vehicleModel'' variable.


<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
function createVehicleForPlayer (thePlayer, command, vehicleModel)
function createVehicleForPlayer(thePlayer, command, vehicleModel)
local x, y, z = getElementPosition (thePlayer) - Získá pozici hráče
local x,y,z = getElementPosition(thePlayer) -- get the position of the player
x = x + 5 - Přidá 5 do polohy X
x = x + 5 -- add 5 units to the x position
- Vytvořit vozidlo a uložení vrácené vozidla prvek v'''' createdVehicle proměnné
-- create the vehicle and store the returned vehicle element in the ''createdVehicle'' variable
local createdVehicle = createVehicle (tonumber (vehicleModel), x, y, z)
local createdVehicle = createVehicle(tonumber(vehicleModel),x,y,z)
end
end
</ Code>
</syntaxhighlight>


Samozřejmě, že tento kód se může zlepšit v mnoha ohledech, ale aspoň chceme přidat kontrolu, zda vozidlo bylo vytvořeno správně nebo ne. Jak se můžeme dočíst na [[createVehicle]] strana pod'' 'se vrací''', tato funkce vrací'' false'', když script nemohl vytvořit vozidlo. Proto jsme zkontrolovali hodnotu'''' createVehicle proměnné.
Of course, this code can be improved in many ways, but at least we want to add a check whether the vehicle was created successfully or not. As we can read on the [[createVehicle]] page under '''Returns''', the function returns ''false'' when it was unable to create the vehicle. Thus, we check the value of the ''createVehicle'' variable.


Nyní máme kompletní skript:
Now we have our complete script:
<syntaxhighlight lang="lua"> [lua]
<syntaxhighlight lang="lua">
function createVehicleForPlayer (thePlayer, command, vehicleModel)
function createVehicleForPlayer(thePlayer, command, vehicleModel)
local x, y, z = getElementPosition (thePlayer) - Získá pozici hráče
local x,y,z = getElementPosition(thePlayer) -- get the position of the player
x = x + 5 - Přidá 5 do polohy X
x = x + 5 -- add 5 units to the x position
local createdVehicle = createVehicle (tonumber (vehicleModel), x, y, z)
local createdVehicle = createVehicle(tonumber(vehicleModel),x,y,z)
- Zkontroluje zda je hodnota false
-- check if the return value was ''false''
if (createdVehicle == false) then
if (createdVehicle == false) then
- Pokud ano, vypíše zprávu do chatu , ale pouze hráči co příkaz použil.
-- if so, output a message to the chatbox, but only to this player.
outputChatBox ("Nepodařilo se vytvořit vozidlo.", thePlayer)
outputChatBox("Failed to create vehicle.",thePlayer)
end
end
end
end
addCommandHandler("createvehicle", createVehicleForPlayer)
addCommandHandler ("createvehicle", createVehicleForPlayer)
</syntaxhighlight>
</ Code>


Jak můžete vidět, jsme zavedli jinou funkci s [[outputChatBox]]. Do teď, měli byste být schopni prozkoumat funkce v dokumentaci stranu sám. Pro více pokročilé skriptování, prosím, podívejte se [[Map manager | Map Manager]].
As you can see, we introduced another function with [[outputChatBox]]. By now, you should be able to explore the function's documentation page yourself. For more advanced scripting, please check out the [[Map manager|Map Manager]].


== Co byste měli vědět ==
==What you need to know==
Už jste si některé věci, o prostředcích, které manipulují s velitelskými a hledání funkcí v dokumentaci v prvním odstavci, ale tam je hodně co učit. Tato sekce vám spíše krátký přehled nad některými z těchto věcí, a zároveň odkazují na související stránky, pokud je to možné.
You already read some things about resources, command handlers, and finding functions in the documentation in the first paragraph, but there is much more to learn. This section will give you a rather short overview over some of these things while linking to related pages if possible.
=== Clientside a serverside skripty ===
===Clientside and Serverside scripts===
Možná jste si již všimli, tyto nebo příbuznými pojmy (Server / Client) někde na této wiki, většinou ve spojení s funkcemi. MTA nejen podporuje skripty, které běží na serveru a poskytují příkazy (jako ta, kterou jsme napsali výše) nebo jiné funkce, ale také skripty, které běží na straně klienta MTA hráči použít k připojení k serveru. Důvodem pro to je, že některé funkce MTA poskytuje musí být clientside (jako GUI - Graphical User Interface), ostatní by měli být proto, že lépe pracovat a ještě jiní jsou na tom lépe být serverside, nebo prostě nefungují clientside.
You may have already noticed these or similar terms (Server/Client) somewhere on this wiki, mostly in conjunction with functions. MTA not only supports scripts that run on the server and provide commands (like the one we wrote above) or other features but also scripts that run on the MTA client the players use to connect to the server. The reason for this is, that some features MTA provides have to be clientside (like a GUI - Graphical User Interface), others should be because they work better and still, others are better off to be serverside or just don't work clientside.


Většina skriptů budete dělat (gamemodes, mapy) bude pravděpodobně serverside, jako ten, který jsme napsali v první části. Pokud se dostanete do něčeho, co nemůže být serverside, budete pravděpodobně muset dělat clientside. Pro clientside skript například, byste vytvořili obyčejný soubor skriptu (například s názvem client.lua) a specifikovat v meta.xml, jako je toto:
Most scripts you will make (gamemodes, maps) will probably be serverside, like the one we wrote in the first section. If you run into something that can't be solved serverside, you will probably have to make it clientside. For a clientside script, for example, you would create an ordinary script file (for example called ''client.lua'') and specify it in the meta.xml, like this:
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
<script src="client.lua" type="client" />
<script src="client.lua" type="client" />
</ Code>
</syntaxhighlight>
Typ atribut výchozí "server", takže stačí zadat to pro clientside skriptů. Když to uděláte, bude clientside skript stáhnut na hráčově počítači jakmile se připojí k serveru. Přečtěte si více o [[skripty na straně klienta]].
The ''type'' attribute defaults to 'server', so you only need to specify it for client-side scripts. When you do this, the clientside script will be downloaded to the player's computer once he connects to the server. Read more about [[Client side scripts]].


=== Složitější zdroje ===
===More complex resources===
Předchozí část ukázala krátce, jak přidat clientside skripty ke zdroji, ale je zde také mnohem více je to možné. Jak již bylo zmíněno na samém vrcholu této stránky, mohou být zdroje skoro všechno. Jejich účelem je definována tím, co dělají. Pojďme si některé teoretické zdroje, při pohledu na soubory, které obsahuje, na'' meta.xml'' a to, co mohl udělat:
The previous section showed briefly how to add clientside scripts to the resource, but there is also much more possible. As mentioned at the very top of this page, resources can be pretty much everything. Their purpose is defined by what they do. Let's have some theoretical resources, by looking at the files it contains, the ''meta.xml'' and what they might do:


==== První příklad - script ====
====First example - A utility script====
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
/ Admin_commands
/admin_commands
/ Meta.xml
/meta.xml
/ Commands.lua
/commands.lua
/ Client.lua
/client.lua
</ Code>
</syntaxhighlight>
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
<meta>
<meta>
<Info author="Someguy" description="admin commands" />
<info author="Someguy" description="admin commands" />
<script src="commands.lua" />
<script src="commands.lua" type="server" />
<script src="client.lua" type="client" />
<script src="client.lua" type="client" />
</ Meta>
</meta>
</ Code>
</syntaxhighlight>


*'''' Commands.lua poskytuje některé admin příkazy, jako ban hráče, mute nebo něco jiného, ​​co lze použít k admin serveru
* The ''commands.lua'' provides some admin commands, like banning a player, muting or something else that can be used to admin the server
*'''' Client.lua poskytuje GUI, aby mohli provádět uvedené akce snadno
* The ''client.lua'' provides a GUI to be able to perform the mentioned actions easily


Tento příklad by mohl být spuštěn po celou dobu (možná i auto-start při startu serveru), jak je to užitečné v průběhu celého herního zážitku a také zvyklý v rozporu s hratelností, pokud admin podnikne nějakou akci samozřejmě.
This example might be running all the time (maybe even auto-started when the server starts) as it's useful during the whole gaming experience and also won't interfere with the gameplay, unless an admin decides to take some action of course.


==== Druhý příklad - gamemode ====
====Second example - A gamemode====
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
/ Counterstrike
/counterstrike
/ Meta.xml
/meta.xml
/ Counterstrike.lua
/counterstrike.lua
/ Buymenu.lua
/buymenu.lua
</ Code>
</syntaxhighlight>
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
<meta>
<meta>
<Info author="Someguy" description="Counterstrike remake" type="gamemode" />
<info author="Someguy" description="Counterstrike remake" type="gamemode" />
<script src="counterstrike.lua" />
<script src="counterstrike.lua" type="server" />
<script src="buymenu.lua" type="client" />
<script src="buymenu.lua" type="client" />
</ Meta>
</meta>
</ Code>
</syntaxhighlight>


*'''' Counterstrike.lua obsahuje příbuznými na následující funkce:
* The ''counterstrike.lua'' contains similar to the following features:
** Ať hráči mohou vybrat svůj tým a hraje s nimi
** Let players choose their team and spawn them
** Poskytněte jim zbraně, a pokyny (možná čtení z mapy, viz níže)
** Provide them with weapons, targets, and instructions (maybe read from a Map, see below)
** Definujte Pravidla hry, např. Kdy kolo končí, co se stane, když hráč zemře
** Define the game's rules, e.g. when does the round end, what happens when a player dies
** .. a možná některé další
** .. and maybe some more
*'''' Buymenu.lua je clientside skript a vytváří nabídku k nákupu zbraní
* The ''buymenu.lua'' is a clientside script and creates a menu to buy weapons


Tento příklad může být nazýván gamemodu, protože to není jen intereferes s hratelností, ale ve skutečnosti definuje pravidla ní. '' Typ'' atribut označuje, že tento příklad pracuje s [[Map manager]], další zdroj, který byl napsán v QA týmu pro správu gamemodes a mapu loading. Důrazně se doporučuje, aby si založit své gamemodes na techniky, které poskytuje.
This example can be called a gamemode, since it not only interferes with the gameplay but actually defines the rules of it. The ''type'' attribute indicates that this example works with the [[Map manager]], yet another resource that was written by the QA Team to manage gamemodes and map loading. It is highly recommended that you base your gamemodes on the techniques it provides.


To také znamená, že gamemodu pravděpodobně nelze spustit bez mapy. Gamemodes by měly být vždy možné míře všeobecné. Příkladem mapě je uvedeno v následujícím příkladu.
This also means that the gamemode probably won't run without a map. Gamemodes should always be as generic as possible. An example of a map is stated in the next example.


==== Třetí příklad - Mapa ====
====Third example - A Map====
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
/ Cs-letiště
/cs-airport
/ Meta.xml
/meta.xml
/ Airport.map
/airport.map
/ Airport.lua
/airport.lua
</ Code>
</syntaxhighlight>
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
<meta>
<meta>
<Info author="Someguy" description="Counterstrike letiště map" type="map" gamemodes="counterstrike" />
<info author="Someguy" description="Counterstrike airport map" type="map" gamemodes="counterstrike" />
<map src="airport.map" />
<map src="airport.map" />
<script src="airport.lua" />
<script src="airport.lua" type="server" />
</ Meta>
</meta>
</ Code>
</syntaxhighlight>


*'''' Airport.map v souboru XML, který poskytuje informace o mapě na gamemodu, mohou zahrnovat:
* The ''airport.map'' in an XML file that provides information about the map to the gamemode, these may include:
** Pokud hráči by měli plodit, s tím, co zbraně, jaké týmy tam jsou
** Where the players should spawn, with what weapons, what teams there are
** Jaké jsou cíle
** What the targets are
** Počasí, Světový čas, časový limit
** Weather, World Time, Timelimit
** Poskytovat vozidla
** Provide vehicles
*'''' Airport.lua může obsahovat mapu specifické rysy, které mohou zahrnovat:
* The ''airport.lua'' might contain map-specific features, that may include:
** Otevření nějaké dveře / udělat něco explodovat, když se něco stane zvláštní
** Opening some door/make something explode when something specific happens
** Vytvoření nebo přesunout některé vlastní objekty, nebo manipulovat s objekty, které jsou vytvořeny pomocí. Souboru mapy
** Create or move some custom objects, or manipulate objects that are created through the .map file
** .. něco jiného mapu specifické můžete myslet
** .. anything else map-specific you can think of


Jak můžete vidět,'''' typu atribut změněn na "mapu", říká [[Map manager]], že tento zdroj je mapa, zatímco'''' gamemodes atribut říká, že pro které gamemodes tuto mapu platí , v tomto případě gamemodu z výše uvedeného příkladu.
As you can see, the ''type'' attribute changed to 'map', telling the [[Map manager]] that this resource is a map, while the ''gamemodes'' attribute tells it for which gamemodes this map is valid, in this case, the gamemode from the above example.
Co může přijít jako překvapení je, že tam je také skript v Map zdroje. Samozřejmě to není nezbytně nutné v mapě, ale otevírá širokou škálu možností pro tvůrci map vytvořit svůj vlastní svět v rámci pravidel gamemodu oni Můžete si jej.
What may come as a surprise is that there is also a script in the Map resource. Of course, this is not necessarily needed in a map but opens a wide range of possibilities for map makers to create their own world within the rules of the gamemode they create it for.


'''' Airport.map soubor může vypadat příbuznými na toto:
The ''airport.map'' file might look similiar to this:
<syntaxhighlight lang="lua"> [xml]
<syntaxhighlight lang="xml">
<map mode="deathmatch" version="1.0">
<map mode="deathmatch" version="1.0">
<terrorists>
<terrorists>
<spawnpoint posX="2332.23" posY="-12232.33" posZ="4.42223" skins="23-40" />
<spawnpoint posX="2332.23" posY="-12232.33" posZ="4.42223" skins="23-40" />
</ Teroristé>
</terrorists>
<counterterrorists>
<counterterrorists>
<spawnpoint posX="2334.23443" posY="-12300.233" posZ="10.2344" skins="40-50" />
<spawnpoint posX="2334.23443" posY="-12300.233" posZ="10.2344" skins="40-50" />
</ Counterterrorists>
</counterterrorists>
 
<bomb posX="23342.23" posY="" posZ="" />
<vehicle posX="" posY="" posZ="" model="602" />
<vehicle posX="" posY="" posZ="" model="603" />
</map>
</syntaxhighlight>


<bomb posX="23342.23" posY="" posZ="" />
When a gamemode is started with a map, the map resources are automatically started by the map-manager and the information it contains can be read by the gamemode resource. When the map changes, the current map resource is stopped and the next map resource is started. For a more in-depth explanation and examples of how map resources are utilized in the main script, please visit the [[Writing Gamemodes]] page.


<vehicle posX="" posY="" posZ="" model="602" />
===Events===
<vehicle posX="" posY="" posZ="" model="603" />
[[Event|Events]] are the way MTA tells scripts about things that happen. For example, when a player dies, the [[onPlayerWasted]] event is triggered. In order to perform any actions when a player dies, you have to prepare yourself similar to adding a command handler, as shown in [[#Writing_the_script|the first chapter]].
</ Map>
</ Code>


Když je gamemodu začal s mapou, je mapa prostředky spouští automaticky mapmanager a informace v něm obsažené lze číst gamemodu zdroje. Když se mapa mění, je aktuální mapa zdrojem zastavil a další mapy zdroj je spuštěn. Pro více in-hloubkové vysvětlení a příklady toho, jak jsou mapy zdroje využívány v hlavním skriptu, navštivte [[Psaní Gamemodes]] stránku.
This example will output a message with the name of the player who died:
<syntaxhighlight lang="lua">
function playerDied(totalAmmo, killer, killerWeapon, bodypart)
outputChatBox(getPlayerName(source).." died!")
end
addEventHandler("onPlayerWasted",getRootElement(),playerDied)
</syntaxhighlight>


Akce === ===
Instead of showing what arguments are needed, the documentation page for Events shows what parameters are passed to the handler function, similar to the way a [[#About_command_handlers|command handler]] does, just that it is different from event to event. Another important point is the ''source'' variable, that exists in handler functions. It doesn't have to be added to the parameter list of the function, but it still exists. It has a different value from event to event, for player events (as in the example above) it is the player element. As another example, you can take a look at the basic spawning player script in the first section to get an idea of how ''source'' is used.
Události jsou způsob, jak MTA říká skripty na věci, které se dějí. Například, když hráč umře, [[onPlayerWasted]] událost je spuštěna. Aby bylo možné provést žádné akce, kdy hráč zemře, budete muset připravit sami příbuznými přidání příkazu rutiny, jak je uvedeno v [[# Writing_the_script | První kapitola]].


Tento příklad vypíše zprávu s názvem hráče, který zemřel:
==Where to go from here==
<syntaxhighlight lang="lua"> [lua]
You should now be familiar with the most basic aspects of MTA scripting and also a bit with the documentation. The [[Main Page]] provides you with links to more information, Tutorials, and References that allow a deeper look into the topics you desire to learn about.
Funkce playerDied (totalAmmo, vrah, killerWeapon, bodypart)
{{note|From here we recommend reading the [[debugging]] tutorial. Good debugging skills are an absolute necessity when you are making scripts. We also recommend you to use the [[predefined variables list]] to help you with certain tasks and make scripting easier and faster.}}
outputChatBox (getPlayerName (zdroj) .. "umřel!")
'''See also:'''
konec
* [[OOP_Introduction|OOP Scripting Introduction]]
addEventHandler ("onPlayerWasted", getRootElement (), playerDied)
* [[Advanced Topics]]
</ Code>
* [[Script_security|Script security]]


Místo ukazuje, jaké argumenty jsou potřeba, dokumentace stránka pro akce ukazuje, jaké parametry jsou předány funkce zpracování, podobně k cestě [[# About_command_handlers | Příkaz handler]] dělá, jen to, že se liší od akce k akci. Dalším důležitým bodem je'''' zdrojem proměnná, která existuje v popisovač funkcí. To nemá být přidán do seznamu parametrů funkce, ale stále ještě existuje. To má jinou hodnotu od události k události, pro hráče události (jako ve výše uvedeném příkladu), že je hráč element. Jako další příklad, můžete se podívat na základní scénář tření hráče v první části, abyste získali představu, jak se používá'''' zdroj.


== Kam jít odsud ==
[[hu:Bevezetés a scriptelésbe]]
Nyní byste měli být obeznámeni se základními aspekty MTA skriptování a také trochu s dokumentací. [[Hlavní stránka]] poskytuje odkazy na další informace, návody a odkazy, které umožňují hlubší pohled do témat, touží dozvědět více.
[[es:Introducción a la Programación]]
{{Note | Odtud doporučujeme přečíst [[ladění]] tutorial. Dobré ladění dovednosti jsou absolutní nutností, když dělají skripty. Také doporučujeme použít [[předdefinované proměnné list]], aby vám pomohl s některými úkoly a aby skriptování jednodušší a rychlejší.}}
[[it:Introduzione allo scripting]]
'' 'Viz také:'''
[[nl:Scripting_introductie]]
* [[Advanced Topics]]
[[pl:Scripting Introduction]]
[[Ru: Skriptování Úvod]]
[[pt-br:Introdução ao Scripting]]
[[It: Introduzione allo skriptování]]
[[ru:Scripting Introduction]]
[[Es: Introducción la Programación]]
[[ar:مقدمه_في_البرمجه]]
[[Nl: Scripting_introductie]]
[[zh-cn:脚本编写介绍]]
[[Category:Tutorials]]

Revision as of 15:00, 15 May 2024

Resources are a key part of MTA. A resource is essentially a folder or zip file that contains a collection of files, plus a "meta" file that describes to the server how the resource should be loaded and what files it does contain. A resource can be seen as being partly equivalent to a program running in an operating system - it can be started and stopped, and multiple resources can run at once.

Everything that has to do with scripting happens in resources, what a resource does defines if it is a gamemode, a map, or anything else. MTA comes with resources that you can optionally use in your gamemodes, such as map limits to keep playings within a playing area or death-pickups to create weapon pickups.

[[{{{image}}}|link=|]] Tip: Your first step to begin Lua scripting should be using a Lua editor. This makes scripting much easier. We recommend Visual Studio Code, Notepad++ or Sublime Text. There is also an unofficial Android mobile app MTA:SA Developers: Mobile that you can try out.

Creating a working script

We will first learn how to make a basic script that lets the player walk around in the city, step by step.

Where are all the scripts?

Let's take a look at the script's file structure. Go to your MTA Server folder, and follow the path below:

server/mods/deathmatch/resources/

You will see a lot of .zip files, which are the packaged sample scripts shipped with MTA. Each file is a "resource", and they will all be unzipped and loaded by the server when it starts. To create your own resource, simply make a folder with your preferred name. We'll use "myserver" for this tutorial.

Now you should be under this directory:

server/mods/deathmatch/resources/myserver/

Identifying your resource

In order to let the server know what's in the resource, a meta.xml file must be created to list the resource's content. It must be located in the resource's root directory, which is the "myserver" folder in our case. So create a text file and name it "meta.xml", and open it with notepad.

Enter the following codes in the meta.xml file:

<meta>
     <info author="YourName" type="gamemode" name="My Server" description="My first MTA server" />
     <script src="script.lua" type="server" />
</meta>

In the <info /> tag, there's a "type" field which indicates that the resource is a gamemode instead of a regular include or a map, which will be explained later. A gamemode is what you need to make a stand-alone server.

The <script /> tag indicates the script files contained in the resource, which we will create next.

Creating a simple script

Note that in the <script /> tag above, the .lua file is not under another directory. Therefore we'll create the file in the same folder as meta.xml. Now you can copy and paste the following code into script.lua:

local spawnX, spawnY, spawnZ = 1959.55, -1714.46, 10
function joinHandler()
	spawnPlayer(source, spawnX, spawnY, spawnZ)
	fadeCamera(source, true)
	setCameraTarget(source, source)
	outputChatBox("Welcome to My Server", source)
end
addEventHandler("onPlayerJoin", getRootElement(), joinHandler)

The script will spawn you at the coordinate (x, y, z) specified above when you join the game. Note that the fadeCamera function must be used or the screen will be black. Also, in releases after DP2, you need to set the camera target (otherwise all the players will see is the blue sky).

The source variable indicates who triggered the event. Since a player has joined when the code is triggered, you use this variable to look which has joined. So it'll spawn that player instead of everyone or a random person.

If we have a closer look on addEventHandler, you can see 3 things: 'onPlayerJoin', which indicates when it's triggered. getRootElement(), which shows by what/who it can be triggered. (getRootElement() is everything/everyone) And joinHandler, which indicates the function that has to be triggered after the event is triggered. Other details will be explained later in another example, now let's just run the server and try it out!

Running the script

To get the server started, simply run the executable under the server/ directory. A list of server stats will be shown first; note the port number, which you'll need when joining the game. Then the server loads all the resources under the mods/deathmatch/resources/ directory, and then "ready to accept connections!"

Before you connect to the server, you must run the gamemode. Type "start myserver" and press Enter. The server will start the gamemode you just created, and will also show any errors and warnings from this point on. Now you can start the MTA client, and "Quick Connect" using the IP address of your server and the port number you saw earlier. If all goes well, after a few seconds your character will be walking on the streets of Los Santos.

Next, we'll add a command to your script that players can use to spawn a vehicle beside their position. You may skip it and check out more advanced scripting with the Map Manager, which continues this tutorial. Another branch from this tutorial is Introduction to Scripting GUI, you may follow it to see how the Graphical User Interface in MTA is drawn and scripted.

Creating a simple command

Let's go back to the content of the script.lua file. As mentioned above, we want to provide a command to create a vehicle beside your current position in the game. Firstly we need to create a function we want to call and a command handler that creates the command the player will be able to enter in the console.

-- create the function the command handler calls, with the arguments: thePlayer, command, vehicleModel
function createVehicleForPlayer(thePlayer, command, vehicleModel)
   -- create a vehicle and stuff
end

-- create a command handler
addCommandHandler("createvehicle", createVehicleForPlayer)

Note: Function names are clickable in code examples on the wiki and linked to the functions' documentation.

About command handlers

The first argument of addCommandHandler is the name of the command the player will be able to enter, the second argument is the function this will call, in this case createVehicleForPlayer.

If you have already experienced in scripting, you will know that you call a function like this:

functionName(argument1, argument2, argument3, ..)
functionName(thePlayer, commandName, argument3, ..)

If we have a closer look on the lower example above, we can see argument1 is thePlayer and argument2 the commandName. thePlayer is simply the one who typed the command, so whatever you call it, the variable will contain the player who activated the command. commandName is simply the command they typed. So if they typed "/greet", this argument will contain "greet". Argument 3 is something extra the player typed, you'll learn it a little bit further in the tutorial. Never forget that the first 2 arguments are standard arguments, but you can name them to anything you want.

We called the addCommandHandler function this way already and since createVehicleForPlayer is a function too, it can be called that way as well. But we are using a command handler for that, which calls it in a similar manner, internally.

For example someone types "createvehicle 468" in-game in the console to spawn a Sanchez, the command handler calls the createVehicleForPlayer function, as if we would have this line of code in the script:

createVehicleForPlayer(thePlayer,"createvehicle","468") -- thePlayer is the player element of the player who entered the command

As we can see, it provides several parameters: the player who called the command, the command he entered, and whatever text he had after that, in this case, "468" as vehicle id for the Sanchez. The first two parameters are the same with all command handlers, which you can read on the addEventHandler page. For this fact, you always have to define at least those two parameters to use any after that (for example to process text that was entered after the command, like in our example the vehicle model id).

Note: You have to add the command handler AFTER you defined the handler function, else it can't find it. The order of execution matters.

Writing the function

In order to fill the function we created, we need to think about what we have to do:

  • Get the players position, so we know where to spawn the vehicle (we want it to appear right beside the player)
  • Calculate the position we want to spawn the vehicle at (we don't want it to appear in the player)
  • Spawn the vehicle
  • Check if it has been spawned successfully, or output a message

In order to achieve our goals, we have to use several functions. To find the function we need to use, we should visit the Server Functions List. First, we need a function to get the player's position. Since players are Elements, we first jump to the Element functions where we find the getElementPosition function. By clicking on the function name in the list, you get to the function description. There we can see the syntax, what it returns, and usually an example. The syntax shows us what arguments we can or have to submit.

For getElementPosition, the syntax is:

float, float, float getElementPosition ( element theElement )

The three float in front of the function name is the return type. In this case, it means the function returns three floating-point numbers. (x, y, and z) Within the parentheses, you can see what arguments you have to submit. In this case, only the element whose position you want to get, which is the player in our example.

function createVehicleForPlayer(thePlayer, command, vehicleModel)
	-- get the position and put it in the x,y,z variables
	-- (local means, the variables only exist in the current scope, in this case, the function)
	local x,y,z = getElementPosition(thePlayer)
end

Next, we want to ensure that the vehicle won't spawn directly in the player, so we add a few units to the x variable, which will make it spawn east from the player.

function createVehicleForPlayer(thePlayer, command, vehicleModel)
	local x,y,z = getElementPosition(thePlayer) -- get the position of the player
	x = x + 5 -- add 5 units to the x position
end

Now we need another function, one to spawn a vehicle. We once again search for it on the Server Functions List, this time - since we are talking about vehicles - in the Vehicle functions section, where we will choose createVehicle. In this function's syntax, we only have one return type (which is more common), a vehicle element that points to the vehicle we just created. Also, we see that some arguments are enclosed within [ ] which means that those are optional.

We already have all arguments we need for createVehicle in our function: The position we just calculated in the x,y,z variables and the model id that we provided through the command ("createvehicle 468") and can access in the function as vehicleModel variable.

function createVehicleForPlayer(thePlayer, command, vehicleModel)
	local x,y,z = getElementPosition(thePlayer) -- get the position of the player
	x = x + 5 -- add 5 units to the x position
	-- create the vehicle and store the returned vehicle element in the ''createdVehicle'' variable
	local createdVehicle = createVehicle(tonumber(vehicleModel),x,y,z)
end

Of course, this code can be improved in many ways, but at least we want to add a check whether the vehicle was created successfully or not. As we can read on the createVehicle page under Returns, the function returns false when it was unable to create the vehicle. Thus, we check the value of the createVehicle variable.

Now we have our complete script:

function createVehicleForPlayer(thePlayer, command, vehicleModel)
	local x,y,z = getElementPosition(thePlayer) -- get the position of the player
	x = x + 5 -- add 5 units to the x position
	local createdVehicle = createVehicle(tonumber(vehicleModel),x,y,z)
	-- check if the return value was ''false''
	if (createdVehicle == false) then
		-- if so, output a message to the chatbox, but only to this player.
		outputChatBox("Failed to create vehicle.",thePlayer)
	end
end
addCommandHandler("createvehicle", createVehicleForPlayer)

As you can see, we introduced another function with outputChatBox. By now, you should be able to explore the function's documentation page yourself. For more advanced scripting, please check out the Map Manager.

What you need to know

You already read some things about resources, command handlers, and finding functions in the documentation in the first paragraph, but there is much more to learn. This section will give you a rather short overview over some of these things while linking to related pages if possible.

Clientside and Serverside scripts

You may have already noticed these or similar terms (Server/Client) somewhere on this wiki, mostly in conjunction with functions. MTA not only supports scripts that run on the server and provide commands (like the one we wrote above) or other features but also scripts that run on the MTA client the players use to connect to the server. The reason for this is, that some features MTA provides have to be clientside (like a GUI - Graphical User Interface), others should be because they work better and still, others are better off to be serverside or just don't work clientside.

Most scripts you will make (gamemodes, maps) will probably be serverside, like the one we wrote in the first section. If you run into something that can't be solved serverside, you will probably have to make it clientside. For a clientside script, for example, you would create an ordinary script file (for example called client.lua) and specify it in the meta.xml, like this:

<script src="client.lua" type="client" />

The type attribute defaults to 'server', so you only need to specify it for client-side scripts. When you do this, the clientside script will be downloaded to the player's computer once he connects to the server. Read more about Client side scripts.

More complex resources

The previous section showed briefly how to add clientside scripts to the resource, but there is also much more possible. As mentioned at the very top of this page, resources can be pretty much everything. Their purpose is defined by what they do. Let's have some theoretical resources, by looking at the files it contains, the meta.xml and what they might do:

First example - A utility script

/admin_commands
	/meta.xml
	/commands.lua
	/client.lua
<meta>
	<info author="Someguy" description="admin commands" />
	<script src="commands.lua" type="server" />
	<script src="client.lua" type="client" />
</meta>
  • The commands.lua provides some admin commands, like banning a player, muting or something else that can be used to admin the server
  • The client.lua provides a GUI to be able to perform the mentioned actions easily

This example might be running all the time (maybe even auto-started when the server starts) as it's useful during the whole gaming experience and also won't interfere with the gameplay, unless an admin decides to take some action of course.

Second example - A gamemode

/counterstrike
	/meta.xml
	/counterstrike.lua
	/buymenu.lua
<meta>
	<info author="Someguy" description="Counterstrike remake" type="gamemode" />
	<script src="counterstrike.lua" type="server" />
	<script src="buymenu.lua" type="client" />
</meta>
  • The counterstrike.lua contains similar to the following features:
    • Let players choose their team and spawn them
    • Provide them with weapons, targets, and instructions (maybe read from a Map, see below)
    • Define the game's rules, e.g. when does the round end, what happens when a player dies
    • .. and maybe some more
  • The buymenu.lua is a clientside script and creates a menu to buy weapons

This example can be called a gamemode, since it not only interferes with the gameplay but actually defines the rules of it. The type attribute indicates that this example works with the Map manager, yet another resource that was written by the QA Team to manage gamemodes and map loading. It is highly recommended that you base your gamemodes on the techniques it provides.

This also means that the gamemode probably won't run without a map. Gamemodes should always be as generic as possible. An example of a map is stated in the next example.

Third example - A Map

/cs-airport
	/meta.xml
	/airport.map
	/airport.lua
<meta>
	<info author="Someguy" description="Counterstrike airport map" type="map" gamemodes="counterstrike" />
	<map src="airport.map" />
	<script src="airport.lua" type="server" />
</meta>
  • The airport.map in an XML file that provides information about the map to the gamemode, these may include:
    • Where the players should spawn, with what weapons, what teams there are
    • What the targets are
    • Weather, World Time, Timelimit
    • Provide vehicles
  • The airport.lua might contain map-specific features, that may include:
    • Opening some door/make something explode when something specific happens
    • Create or move some custom objects, or manipulate objects that are created through the .map file
    • .. anything else map-specific you can think of

As you can see, the type attribute changed to 'map', telling the Map manager that this resource is a map, while the gamemodes attribute tells it for which gamemodes this map is valid, in this case, the gamemode from the above example. What may come as a surprise is that there is also a script in the Map resource. Of course, this is not necessarily needed in a map but opens a wide range of possibilities for map makers to create their own world within the rules of the gamemode they create it for.

The airport.map file might look similiar to this:

<map mode="deathmatch" version="1.0">
	<terrorists>
		<spawnpoint posX="2332.23" posY="-12232.33" posZ="4.42223" skins="23-40" />
	</terrorists>
	<counterterrorists>
		<spawnpoint posX="2334.23443" posY="-12300.233" posZ="10.2344" skins="40-50" />
	</counterterrorists>

	<bomb posX="23342.23" posY="" posZ="" />
	
	<vehicle posX="" posY="" posZ="" model="602" />	
	<vehicle posX="" posY="" posZ="" model="603" />	
</map>

When a gamemode is started with a map, the map resources are automatically started by the map-manager and the information it contains can be read by the gamemode resource. When the map changes, the current map resource is stopped and the next map resource is started. For a more in-depth explanation and examples of how map resources are utilized in the main script, please visit the Writing Gamemodes page.

Events

Events are the way MTA tells scripts about things that happen. For example, when a player dies, the onPlayerWasted event is triggered. In order to perform any actions when a player dies, you have to prepare yourself similar to adding a command handler, as shown in the first chapter.

This example will output a message with the name of the player who died:

function playerDied(totalAmmo, killer, killerWeapon, bodypart)
	outputChatBox(getPlayerName(source).." died!")
end
addEventHandler("onPlayerWasted",getRootElement(),playerDied)

Instead of showing what arguments are needed, the documentation page for Events shows what parameters are passed to the handler function, similar to the way a command handler does, just that it is different from event to event. Another important point is the source variable, that exists in handler functions. It doesn't have to be added to the parameter list of the function, but it still exists. It has a different value from event to event, for player events (as in the example above) it is the player element. As another example, you can take a look at the basic spawning player script in the first section to get an idea of how source is used.

Where to go from here

You should now be familiar with the most basic aspects of MTA scripting and also a bit with the documentation. The Main Page provides you with links to more information, Tutorials, and References that allow a deeper look into the topics you desire to learn about.

[[{{{image}}}|link=|]] Note: From here we recommend reading the debugging tutorial. Good debugging skills are an absolute necessity when you are making scripts. We also recommend you to use the predefined variables list to help you with certain tasks and make scripting easier and faster.

See also: