Куда кидать lua файлы в гаррис мод
Урок 3: https://gamesubject.com/question/3026
Создадим фрейм с кнопкой, при нажатии на которую, будет писаться текст в чат, а вызываться фрейм будет через консольную команду.
Писать будем в клиентской части.
Создаём консольную команду:
concommand.Add("start_frame",function(ply,cmd,args)
Теперь пишем, что будет выполнять консольная команда.
Создаём переменную, через которую создаём фрейм:
local Frame = vgui.Create("DFrame")
vgui.Create - создаёт vgui. Работает только в клиентской части.
DFrame - фрейм.
Создаём фрейму заголовок:
Frame:SetTitle("Color button")
SetTitle - создаёт заголовок.
Создаём фрейму размер:
Frame:SetSize(300,300)
SetSize - создаёт размер.
Центрируем фрейм:
Frame:Center()
Center() - центрирует.
Создаём фрейму кнопку закрытия:
Frame:ShowCloseButton(true)
ShowCloseButton - создаёт кнопку закрытия.
Сделаем так, что бы при создании фрейма, мышка была видна:
Frame:MakePopup()
MakePopup() - делает так, что бы мышка была видна.
Нарисуем фрейм:
function Frame:Paint(w,h)
draw.RoundedBox(3,0,0,w,h,Color(255,93,0,200))
end
Paint(w,h) - функция, которая рисует и в переменную w передаёт размер VGUI по ширине, а в переменную h передаёт размер VGUI по высоте.
draw.RoundedBox - рисует закруглённый квадрат.
3 - закругление.
0 - позиция по широте.
0 - позиция по высоте.
w - размер по ширине.
h - размер по высоте.
Color(255,93,0,200) - цвет.
Создаём переменную, через которую создаём кнопку:
local Button = vgui.Create("DButton", Frame)
DButton - кнопка.
Frame - то, куда помещаем кнопку.
Теперь создаём размер кнопке и центрируем её:
Button:SetSize(100,50)
Button:Center()
Создаём текст кнопке: Button:SetText("Press Button")
SetText - создаёт текст.
Теперь сделаем функцию нажатия на кнопку:
function Button:DoClick()
DoClick() - нажатие.
Теперь создаём переменную, в которую помещаем игрока:
local ply = LocalPlayer()
Теперь создаём переменную, в которую помещаем имя игрока:
local name = ply:GetName()
Теперь пишем в чат:
chat.AddText(Color(255,93,0),name.." Press button")
chat.AddText - пишет в чат. Работает только в клиентской части.
Color(255,93,0) - создаём цвет тексту.
name.." Press button" - текст.
Код который у нас получился:
if CLIENT then
concommand.Add("start_frame",function(ply,cmd,args)
local Frame = vgui.Create("DFrame")
Frame:SetTitle("Color button")
Frame:SetSize(300,300)
Frame:Center()
Frame:ShowCloseButton(true)
Frame:MakePopup()
function Frame:Paint(w,h)
draw.RoundedBox(3,0,0,w,h,Color(255,93,0,200))
end
local Button = vgui.Create("DButton", Frame)
Button:SetSize(100,50)
Button:Center()
Button:SetText("Press Button")
function Button:DoClick()
local ply = LocalPlayer()
local name = ply:GetName()
chat.AddText(Color(255,93,0),name.." Press button")
end
end)
end
Garry’s Mod
print( "Hello world" )
Ну что, вроде бы просто? Не так ли? Теперь разберём что это значит.
print() - функция. Функция является командой которая выполняет определённое действие когда вы его объявили. То есть если бы мы не написали функцию print() а сразу просто "Hello World" то нечего бы не произошло. Так как машина бы не распознала команду, которую ей следует выполнять. Многие функции могут принимать аргументы то есть те данные, которые вы отправляете в функцию что бы выполнить определённое действие. В нашем случае print() принимает один аргумент, который является строчным типом данных, то есть стрингом (в англ. string - строка) и выводит этот стринг на экран пользователя. Стринги могут принимать разные значения которые берутся в кавычки, то есть числа, слова, пробелы и многое другое. В нашем случае когда выполняется команда Msg(), то в строчку в консоли Garry's Mod пишется фраза "Hello World".
Сохранение lua-скриптов
Теперь вы готовы сохранить свой код. Для этого перейдите по следующему пути (на разных компьютерах он может отличаться, но будет выглядеть примерно так):
В поле "имя файла" введите hello_world.lua (Обратите внимание, что необходимо указать .lua), а в поле "тип файла" выберите пункт "все файлы" и просто нажмите Enter или кнопку "сохранить" для сохранения скрипта.
Выполнение lua-скрипта
Для запуска любого вашего скрипта вам необходимо зайти в игру и зайти на любую карту в одиночной игре (в мультиплеере часто отключают выполнение сторонних скриптов от игроков, в целях безопасности). Для того что бы запустить ваш скрипт, вам нужно прописать следующую строчку в консоль:
Автозапуск ваших скриптов
Для автоматического запуска ваших скриптов при заходе в игру, вам нужно переместить файл вашего скрипта в следующую папку:
Данная папка будет запускать ваш скрипт автоматически при заходе на сервер или в одиночную игру (на сервере будет запускаться лишь тогда, когда запуск скриптов разрешён администраторами).
Для автоматического запуска вашего скрипта только на клиенте (только в одиночной игре), переместите файл вашего скрипта в следующую папку:
Для автоматического запуска вашего скрипта только на сервере, переместите файл скрипта в следующую папку:
Для этого конкретного урока любой из этих путей будет работать нормально.
я хочу закинуть на сервер очень нужные мне аддоны а в интернете и нету а если я их ставлю то возникает ошибка луа при заходе на сервер, но в воркшопе они есть и я хочу скачать с воркшопа но там формат gma и на сервере они не работают
garry's mod 13 лицензия, сервер тоже на лицензии.
javok (04.12.2012, 10:29) писал: я хочу закинуть на сервер очень нужные мне аддоны а в интернете и нету а если я их ставлю то возникает ошибка луа при заходе на сервер, но в воркшопе они есть и я хочу скачать с воркшопа но там формат gma и на сервере они не работают
garry's mod 13 лицензия, сервер тоже на лицензии.
Там где 1 - пишем номер по счету которым идет аддон.
Там где 104486940 прописываем ID аддона из воркшопа, числа которые идут в конце ссылки.
EginKaman (04.12.2012, 17:21) писал: Делается все намного проще. Создаем файл workshop.vdf в котором прописываем слудющее:
php code:
"addons"
"1" "104486940" // GM_BigCity
"2" "104523837" // Innercity
>
Там где 1 - пишем номер по счету которым идет аддон.
Там где 104486940 прописываем ID аддона из воркшопа, числа которые идут в конце ссылки.
куда этот файл кидать ?
EginKaman (04.12.2012, 17:21) писал: Делается все намного проще. Создаем файл workshop.vdf в котором прописываем слудющее:
php code:
"addons"
"1" "104486940" // GM_BigCity
"2" "104523837" // Innercity
>
Там где 1 - пишем номер по счету которым идет аддон.
Там где 104486940 прописываем ID аддона из воркшопа, числа которые идут в конце ссылки.
куда этот файл кидать ?
ну вот у меня код
"addons"
"1" "107257490" // advanced_ball_socket_tool_(adv._ballsocket)
"2" "104818321" // buoyancy_tool
"3" "104479467" // door_stool
"4" "105115318" // fading_door_stool_105115318
"5" "105899137" // fin_tool_105899137
"6" "111364507" // henrys_animation_tool_111364507
"7" "110103494" // make_spherical_(spherical_collisions_tool)_110103494
"8" "105841291" // more_materials__105841291
"9" "111929524" // multi-parent__unparent_tool_111929524
"10" "106176432" // new_gold_materials_106176432
"11" "104482426" // no_collide_all_multi_104482426
"12" "105955548" // no_collide_everything_105955548
"13" "104634865" // no_collide_world_[reupload]_104634865
"14" "104527283" // offset_trails_104527283
"15" "104691717" // pac3_104691717
"16" "104575630" // ragdoll_mover_104575630
"17" "106944414" // rt_camera_106944414
"18" "104832113" // simple_cross_hair_reupload_104832113
"19" "107388767" // smart_freezer_tool_107388767
"20" "107382750" // smart_remover_tool_107382750
"21" "104815552" // smartsnap_104815552
"22" "109736436" // super-parent_multi_109736436
"23" "105543612" // turbo_constraint_multi_105543612
"25" "107821465" // npc_spawn_platforms_v2.1_107821465
"26" "108941774" // acf_weight_tool_108941774
"27" "113456714" // advanced_duplicator_113456714
"28" "112080049" // nanti_weapon_spawn_server_112080049
"29" "113583962" // axis_center_113583962
"30" "112388171" // builder_112388171
"31" "112330322" // cinematic_moving_camera_112330322
"32" "104516493" // nomad_104516493
"33" "104479831" // stacker_stool_104479831
"34" "109724869" // swep_construction_kit_109724869
"35" "113485508" // unofficial_wire_extras_113485508
"36" "104480013" // weight_stool_104480013
>
но почти все аддоны не робят
javok78 (17.12.2012, 13:02) писал: ну вот у меня код
"addons"
"1" "107257490" // advanced_ball_socket_tool_(adv._ballsocket)
"2" "104818321" // buoyancy_tool
"3" "104479467" // door_stool
"4" "105115318" // fading_door_stool_105115318
"5" "105899137" // fin_tool_105899137
"6" "111364507" // henrys_animation_tool_111364507
"7" "110103494" // make_spherical_(spherical_collisions_tool)_110103494
"8" "105841291" // more_materials__105841291
"9" "111929524" // multi-parent__unparent_tool_111929524
"10" "106176432" // new_gold_materials_106176432
"11" "104482426" // no_collide_all_multi_104482426
"12" "105955548" // no_collide_everything_105955548
"13" "104634865" // no_collide_world_[reupload]_104634865
"14" "104527283" // offset_trails_104527283
"15" "104691717" // pac3_104691717
"16" "104575630" // ragdoll_mover_104575630
"17" "106944414" // rt_camera_106944414
"18" "104832113" // simple_cross_hair_reupload_104832113
"19" "107388767" // smart_freezer_tool_107388767
"20" "107382750" // smart_remover_tool_107382750
"21" "104815552" // smartsnap_104815552
"22" "109736436" // super-parent_multi_109736436
"23" "105543612" // turbo_constraint_multi_105543612
"25" "107821465" // npc_spawn_platforms_v2.1_107821465
"26" "108941774" // acf_weight_tool_108941774
"27" "113456714" // advanced_duplicator_113456714
"28" "112080049" // nanti_weapon_spawn_server_112080049
"29" "113583962" // axis_center_113583962
"30" "112388171" // builder_112388171
"31" "112330322" // cinematic_moving_camera_112330322
"32" "104516493" // nomad_104516493
"33" "104479831" // stacker_stool_104479831
"34" "109724869" // swep_construction_kit_109724869
"35" "113485508" // unofficial_wire_extras_113485508
"36" "104480013" // weight_stool_104480013
>
но почти все аддоны не робят
неа нифига nocolide не робит, мне бы хотябы nocolide multi найти чтоб работал и еще распаковщик тоже уже не работает вообще ни как не могу вытащить аддоны из гма
A tutorial that will guide you through scripting in lua with Garry's Mod so that you may create the many things you've always wanted. You will learn the basics, because that's all you really need, and you will learn how to use the wiki, create addons, and gamemodes.
1
1
1
26,408 | уникальных посетителей |
820 | добавили в избранное |
What can Lua do on Gmod? Lua can help you create add-ons like the ones in the workshop. You can use it to control objects in-game, create an admin system, or anything you want, as long as you know how to do it.
Firstly you need to put all your lua scripts in -
C:\Program Files\Steam\SteamApps\Common\garrysmod\garrysmod\lua
Or if your running a server, you can put it in there.
Now you need to enable the console on Garry's Mod if you already haven't.
1.) Start Garry's Mod.
2.) Go to Options.
3.) Go to the Keyboard Tab.
4.) Click the Advanced button.
5.) Check Enabled developer console, then click Okay.
6.) Click Okay again. Now your console will open when you press "~" on your keyboard.
Now, start a game, after that open the console, and you can put lua_openscript fileName.lua to start it server side, to start it client side put lua_openscript_cl fileName.lua in the console. It should run unless you have errors, the errors will appear if that file does not exist, or theres a problem in your lua file.
These will not work if your on someon else's server, it can be only on your own, unless you have some kind of special access to their server.
What printing does is that it prints to a developer console to post a message, this is basically used to print out errors in the console so developers can fix the issues. But it can also be used for anything. The cool thing is that print(); can take in any variable, bellow i will show you examples.
Printing normal text
Adding variables along with text
Today we will be learning about Variables, now the first thing I need to show you is different Variable Types. Below is an example of all them.
Firstly to make a Variable itself just make a name without spaces, or any special characters, but to replace spaces, use "_" ( Underscore ). Then make an equals sign after that, and make it equal anything that is specified up-top in the Variable Types.
Name = "Arnold"; //String Variable Health = 100; //Integer Variable Dead = false; //Boolean Variable VariableName = AnyValue;
String Variable Rules
Boolean Variable Rules
In boolean variables they can only equal true, or false. They do not require quotations because they are not normal text.
Number Variable Rules
Now this works for all Number Variable Types, they do not also require quotations because they are not normal text, and they are to be only numbers!
When using variables all you have to do to use them is reference the name, but make sure they are exactly the same! In programming it is "Caps Sensetive", meaning it has to have capitals if the variable has capital letters in it. Same with everything else which we will be learning! When referencing variables it does not need Quotations, otherwise it thinks your writing normal text, but really your trying to use a variable in code.
To add to a variable?
Num1 = 25; Num2 = 78; Sum = Num1 + Num2; or Sum = Num1 - Num2; or Sum = Num1 * Num2; or Sum = Num1 / Num2;
To add to itself?
Number = 10 Number = Number + 28; or Number = Number - 28; or Number = Number * 28; or Number = Number / 28;
In this we will be learning how to use the If then Statement for making checks in your programs. First of all what is an If Then Else statement? Well they are pieces of code used to check numbers, booleans, and text to do certain things, below is an example of how it works!
Okay so one thing we need to talk about are Semi-Colons, usually you need semi-colons to end a line of code, but if it's a grouping such as the if then else statement, or methods, etc. then they are not required. Another thing to talk about is how to end groupings ( if then else statement, or methods, etc. ), always when your using groupings you need to end it with "end" otherwise the code will not work properly, and could most likely output errors.
Now in this we will learn how to use else, which is used to do something else if it doesn't equal.
Now what this does is that if Health does not equal 0 then it puts him as alive. You can also do else if, although the else if is part of the if then up-top it still need another end because its another grouping. below is an example.
Alright so basically what a function is, is it's a group of code that can be started as many times as you like without re-writing the code multiple times, very suggested that you use this! By the way a method, and a function is the same thing just that in Object-Orientated Programming a method is contained in a class.
Okay so remember how I said that functions are also groupings? Well if you remember, groupings have to have endings just like If Then Statements! What is the parameters in the parentheses? Well in there is what you want to pass, so that the function can use that value. All it really is, is that it's a variable in those parentheses. An example of how it works should help you!
Why did I reference a function in print? Well the reason I did that is because when you make a function return something shown up-top, it acts like a variable, this is very useful! Go ahead and try this for yourself, it will help give you a better understanding of how it works! Here is another example by the way.
-Output: Hello World!
You don't need to return anything, this is your choice to do.
Arrays are variables with lists, arrays can be 1-D, 2-D, or 3-D. 1-D Arrays mean they only have 1 list, 2-D Arrays have more than 2 lists, 3-D Arrays are just cluster ♥♥♥♥♥, quite literally most people get stuck at this point because it's hard to think about. Anyways just think of a 3-D graph as for a 3-D Array. Heres how it's setup.
Really confusing huh? I know how you felt when I first started. Anyways to get the values, you need to label the index for example.
1D_Array[1] --1st Value | Aaron 2D_Array[1][2] --1st List, 2nd Value | David 3D_Array[1][2][3] --1st List (3D), 2nd List (2D), 3rd Value | Denis
Okay so heres something important you need to know, try to lessen the use of while loops, they can be a problem! Usualy while loops are to loop unless an arguement returns the opposite in the arguemnts, I'll show you an example!
Now this while loop will loop forever because true is true. Here will be another example of toggling loops.
This will loop constantly until Tof is false.
For loops are the most common used loop. Mostly they are used to get every individual index in an Array, which you will learn how later. Here is example of how it works.
Okay so here is how it works, i = 1 is the starting value, 10 is the max number it will go to, 1 is how many it will add or subtract to the i variable. Now here is an example how to work it with arrays in 2 different ways.
-Output:
1: Aaron
2: Denis
3: Dave
4: Cherell
Here is another way.
-Output:
1: Aaron
2: Denis
3: Dave
4: Cherell
Make sure to try these in the actual game!
In this section you will be learning what is a Client, and a Server and why they matter in Lua.
Servers usually handle most information, they not only just handle information to keep the load off of Clients to handle themselves, but they keep information safe from the clients from editing them, such as Health, Max Health, Attack, Speed, Experience, Levels, and all kinds of other stats games use. It is safe to give clients access to what attack they have, or health, or any kind of stats the players own, but they cannot have the ability to edit them, or you will see a lot of people hacking your game because you didn't keep player stats safe on the server.
We can learn from this that all of the Players Stats in Gmod will be on the Server Side of the game. So when editing a player stat, make sure to edit it on the Server Side, and not the Client Side.
Here I will be showing you how to use Face Punch's Gmod Lua Wiki. For instance you will be able to look up functions, variables, and what side they're on (Refering to Client, Server, or Shared).
Hooks are like events that happen, but they allow certain things to be done when a certain event happens, this can be very useful! Like for example you want to send a message to a person who joined, thats what a hook basically is.
There are four ways to setup a hook! Here are some examples below.
function playerJoin( ply ) ply:PrintMessage( HUD_PRINTTALK, "Welcome to the server " .. ply:GetName() .. "!" ); end hook.Add( "PlayerInitialSpawn", "First_Spawn", playerJoin );
hook.Add( "PlayerInitialSpawn", "First_Spawn", function( ply ) ply:PrintMessage( HUD_PRINTTALK, "Welcome to the server " .. ply:GetName() .. "!" ); end );
These basicly will not override the current existing hook, but instead will add another. If you do want to override the hook, which you should avoid doing unless you want to override the default hook, heres how you do it. At all costs do your best to avoid overriding hooks.
GAMEMODE["PlayerInitialSpawn"] = function() ply:PrintMessage( HUD_PRINTTALK, "Welcome to the server " .. ply:GetName() .. "!" ); end
GM:PlayerInitialSpawn(ply) ply:PrintMessage( HUD_PRINTTALK, "Welcome to the server " .. ply:GetName() .. "!" ); end
Timers help for delayed tasks, they're always used inside Video Games to help make delay to commands so that code is executed at the appropiate time that you want. An example would be remove a created prop 2 seconds after creation.
hook.Add("PlayerSpawnedProp", "Remove Created Props 2 Sec After", function (ply, mdl, prop) timer.Create("Remove_Prop", 2, 1, function () prop:Remove() end) end)
The first parameter passed in the timer.Create function is the title of the timer, the second parameter is the delay in seconds, the third parameter is the total times you want to loop this timer for, you can set this to 0 if you want it to loop an unlimited amount of times, and the last parameter is the function you want your timer to call when it's time has ended.
After the timer ends, and still has a couple loops left to go, the function is still called, and is called after each loop when the timer is at 0.
In this tutorial you will learn how to add Scripted Entities that do things to your likings. This example was copied from another site, but I will try to help explain it more, I will also teach you the places you can place this as well.
Step 1 - Create a new folder in garrysmod/addons/, and call it what you want your scripted entity to be. When you're finished the path should now look somewhat like this. garrysmod/addons/entity_name.
Step 2
include('shared.lua') function ENT:Draw() -- self.BaseClass.Draw(self) -- Overrides Draw self:DrawEntityOutline( 1.0 ) -- Draw an outline of 1 world unit. self:DrawModel() -- Draws Model Client Side AddWorldTip( self:EntIndex(), "BATHTUB TIME!", 0.5, self:GetPos(), self ) -- This is not required, infact if you're hosting a different gamemode, I suggest you remove this, because I think this might be only in Sandbox. end
AddCSLuaFile( "cl_init.lua" ) -- Make sure clientside AddCSLuaFile( "shared.lua" ) -- and shared scripts are sent. include('shared.lua') function ENT:Initialize() self:SetModel( "models/props_interiors/BathTub01a.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) -- Make us work with physics, self:SetMoveType( MOVETYPE_VPHYSICS ) -- after all, gmod is a physics self:SetSolid( SOLID_VPHYSICS ) -- Toolbox local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end end function ENT:Use( activator, caller ) return end function ENT:Think() -- We don't need to think, we are just a prop after all! end
ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName= "Bath" ENT.Author= "Mruno" ENT.Contact= "Via steam" ENT.Purpose= "Exemplar material" ENT.Instructions= "Use wisely" ENT.Spawnable = true ENT.AdminSpawnable = false
Данная статья предполагает, что вы играете на сервере, где разрешены кастомные скрипты.
VAC-бан исключён, если на сервере разрешены кастомные скрипты, и вы смогли загрузить его командой, не используя обход.
noclip.lua нужно положить в папку, с расположением: ..Steam/steamApps/common/Garry's mod/garrysmod/lua
Команда загрузки скрипта: lua_openscript_cl noclip.lua
Активация меню - Insert.
MAIN-CONFIG - Главная отличительная черта данного скрипта - возможность сохранить все изменения в отдельный файл для каждого сервера, в названии файла название сервера. Файлов можно сохранить неограниченное количество, но при списке больше 50 файлов - иногда происходит баг при загрузке, и меню не закрывается, от чего игра становится невозможно - не создавайте слишком много сейвов. В меню можно перезагрузить сам скрипт, можно выключить его (panic key - кнопка disable справа вверху в окне чита.
Aimbot - гибкий в настройке автоприцел, способный стрелять по частям тела, наводиться лишь по тем кто находится в поле зрения - и наоборот, по тем кто находится за стенами. Присутствует FOV и эффект смягчения наведения для тех, кто предпочитает "сильно не палиться".
ESP - Гибкий в настройке ESP (Впрочем, тут почти во всём гибкая настройка)
Возможность включить фильтр отрисовки; Друзья, Враги, Команда(те, у кого такой же скин), NPC, Наблюдатели.
Возможность выбрать элементы для отображения: Ник, здоровье, оружие, дистанция, здоровье(шкала), команда(цвет), коробка(квадрат/3D прямоугольник).
Возможность включить отрисовку entity, список которых составляется вручную, так же поддерживается коробка
Misc - Возможность выбрать для отображения в небольшом окне слева вверху админов и наблюдателей.
Манипулятор временем позволяет ускорить игровое время, но это не дает спидхака, и не ускоряет получение зарплаты/возрождение, поскольку работает лишь у хоста сервера.
Не до конца понятно, зачем эта функция была добавлена.
ENTS[/color - Управление списком интересных вам entity сервера с функцией обновления спика, очищения списка, сохранения набора entity в отдельный файл (не путать с config - это отдельное меню и отдельные файлы, которые не видны из других менеджеров сохранения)
FRIENDS - Список друзей составленный по SteamId с отображением ников. После составления его можно переключить в список врагов. Внимание - если нажать Friends is enemy до составления списка - вы не сможете переместить человека ни в список друзей, ни в список врагов - почему-то свитчер перестает работать в этом случае. Составляйте заранее.
CAMS - Функция, в честь которой назван сам скрипт. Позволяет открепить камеру от пользователя, имитируя вид от третьего лица (консольный thirdperson), либо вовсе открепить от игрока и летать ей по карте. Она проходит стены и дает весьма не слабый потенциал для вора на Dark RP, трейтора в TTT или убийцы в Murder. Регулятор скорости полёта камеры прилагается.
Почти бесполезные функции, но всё же присутствующие и требующие описания.
bhop, который не дает бонуса скорости почти нигде. Тем не менее, присутствуют функции движения боком для более успешной распрыжки, автоматических стрейфов, движения со скоростью прыжка, автоматического прыжка и движения по углам поворота - "W only". Данная функция поворачивает ваш скин под углами, позволяющая прыгать назад, смотря вперед, при этом чтобы вас все видели, будто вы прыгаете нормально - смотря туда, куда прыгая. Удобно при побеге.
Test 10 и 11 - тестовые функции, которые пока не реализованы. Пустые окна.
Читайте также: