Difference between revisions of "ConVars (SourceMod Scripting)/ru"

From AlliedModders Wiki
Jump to: navigation, search
m
Line 1: Line 1:
ConVars are ''con''sole ''var''iables.  They store string, float, or numerical values. These values can be changed via the console or .cfg files, and sometimes even persist across server sessions.
+
Квары - ''это консольные переменные.'' Они могут иметь числовое или строчное значение. Их значения могут быть изменены через консоль или с помощью .cfg файлов, а иногда сохраняются для всех сеансов сервера.
  
=Introduction=
+
=Введение=
ConVars are accessed through Handles. There are two ways to obtain a ConVar Handle. You can either create a new ConVar, or find an existing one. If you create a ConVar that already exists, it will automatically re-use the old one.
+
Квары доступны через Handle`s. Есть 2 способа получить Handle квара. Создать новый квар или найти существующий. Если вы создадите уже существующий квар, автоматически будет использоваться старый.
  
''Note: ConVar Handles are unique to the ConVar, and do not need to be freed or "uncreated."  They exist until SourceMod is unloaded.''
+
''Примечание: Handle`s для кваров являются уникальными, их не нужно закрывать или присваивать INVALID_HANDLE. Они должны существовать пока SourceMod запущен.''
  
==Finding ConVars==
+
==Поиск кваров==
Finding ConVars is very simple. For example, let's say you want to use <tt>mp_startmoney</tt> from Counter-Strike:Source:
+
Искать квары очень просто. Например, вы хотите найти <tt>mp_startmoney</tt> из Counter-Strike:Source:
  
 
<pawn>new g_hStartMoney
 
<pawn>new g_hStartMoney
Line 16: Line 16:
 
}</pawn>
 
}</pawn>
  
''Note: FindConVar() will return ''<tt>INVALID_HANDLE</tt>'' if the ConVar is not found.  Keep this in mind if you are trying to read ConVars from other plugins.''
+
''Примечание: FindConVar() вернет ''<tt>INVALID_HANDLE</tt>'' если квар не найден.  Keep this in mind if you are trying to read ConVars from other plugins.''
  
==Creating ConVars==
+
==Создание кваров==
A simple ConVar only requires two parameters, a name and a default value. However, it's a good idea to include a description:
+
Простейший квар требует всего 2 значения: имя и значение по умолчанию. Тем не менее, он может содержать описание:
  
 
<pawn>new Handle:g_hEnabled
 
<pawn>new Handle:g_hEnabled
Line 25: Line 25:
 
public OnPluginStart()
 
public OnPluginStart()
 
{
 
{
g_hEnabled = CreateConVar("myplugin_enabled", "1", "Sets whether my plugin is enabled")
+
g_hEnabled = CreateConVar("myplugin_enabled", "1", "Включение/Выключение плагина.")
 
}</pawn>
 
}</pawn>
  
You can also specify value constraints. For example, let's create a cvar called <tt>myplugin_ratio</tt> which cannot go above 1.0 or below 0.1.
+
Вы так же имеете возможностю ограничить значение. Например, давайте создадим квар названием <tt>myplugin_ratio</tt>, который не может быть выше 1,0 и ниже 0,1.
 
<pawn>new Handle:g_hEnabled
 
<pawn>new Handle:g_hEnabled
  
Line 36: Line 36:
 
"0.6",
 
"0.6",
 
"Sets a vote ratio",
 
"Sets a vote ratio",
_, /* Flags will be discussed later */
+
_, /* Флаги (будут обсуждаться позже) */
true, /* Has a minimum */
+
true, /* Включить минимальное значение */
 
0.1,
 
0.1,
true, /* Has a maximum */
+
true, /* Включить максимальное значение */
 
1.0)
 
1.0)
 
}</pawn>
 
}</pawn>
  
The default value can be any type of data, and it does not restrict future data types that can be used. However, the minimum and maximum constraints always interpret the value as a float.
+
Значение по умолчанию может иметь любой тип данных, и оно не ограничивает будущие типы данных, которые можно использовать. Тем не менее, минимальные и максимальные ограничения всегда должны быть числом с плавающей точкой (float).
  
If you create a ConVar that already exists, you will receive a Handle to that ConVar. Furthermore, the Handle itself will be identical, as neither plugin will own the Handle. The description, default value, or constraints will not be changed.
+
Если вы создаете квар, который уже существует, вы получите Handle на этот квар. Кроме того, сами Handle будут идентичны, поскольку плагин будет владеть Handle. Описание, значение по умолчанию, или ограничения не будут изменены.
  
=Using/Changing Values=
+
=Использование/Изменение значений=
Managing ConVars is very simple. For example, let's say we want to change <tt>mp_startmoney</tt>, but save the old value and restore it later. Re-using our <tt>mp_startmoney</tt> code from <tt>FindConVar</tt>:
+
Использовать квары очень просто. Например, мы хотим изменить <tt>mp_startmoney</tt>, но сохранить старое значение и восстановить его позже. Повторно используем наш код <tt>mp_startmoney</tt> от раздела <tt>Получение кваров</tt>:
  
 
<pawn>new g_oldmoney
 
<pawn>new g_oldmoney

Revision as of 15:38, 6 January 2014

Квары - это консольные переменные. Они могут иметь числовое или строчное значение. Их значения могут быть изменены через консоль или с помощью .cfg файлов, а иногда сохраняются для всех сеансов сервера.

Введение

Квары доступны через Handle`s. Есть 2 способа получить Handle квара. Создать новый квар или найти существующий. Если вы создадите уже существующий квар, автоматически будет использоваться старый.

Примечание: Handle`s для кваров являются уникальными, их не нужно закрывать или присваивать INVALID_HANDLE. Они должны существовать пока SourceMod запущен.

Поиск кваров

Искать квары очень просто. Например, вы хотите найти mp_startmoney из Counter-Strike:Source:

new g_hStartMoney
 
public OnPluginStart()
{
	g_hStartMoney = FindConVar("mp_startmoney")
}

Примечание: FindConVar() вернет INVALID_HANDLE если квар не найден. Keep this in mind if you are trying to read ConVars from other plugins.

Создание кваров

Простейший квар требует всего 2 значения: имя и значение по умолчанию. Тем не менее, он может содержать описание:

new Handle:g_hEnabled
 
public OnPluginStart()
{
	g_hEnabled = CreateConVar("myplugin_enabled", "1", "Включение/Выключение плагина.")
}

Вы так же имеете возможностю ограничить значение. Например, давайте создадим квар названием myplugin_ratio, который не может быть выше 1,0 и ниже 0,1.

new Handle:g_hEnabled
 
public OnPluginStart()
{
	g_hEnabled = CreateConVar("myplugin_ratio",
			"0.6",
			"Sets a vote ratio",
			_,	/* Флаги (будут обсуждаться позже) */
			true,	/* Включить минимальное значение */
			0.1,
			true,	/* Включить максимальное значение */
			1.0)
}

Значение по умолчанию может иметь любой тип данных, и оно не ограничивает будущие типы данных, которые можно использовать. Тем не менее, минимальные и максимальные ограничения всегда должны быть числом с плавающей точкой (float).

Если вы создаете квар, который уже существует, вы получите Handle на этот квар. Кроме того, сами Handle будут идентичны, поскольку плагин будет владеть Handle. Описание, значение по умолчанию, или ограничения не будут изменены.

Использование/Изменение значений

Использовать квары очень просто. Например, мы хотим изменить mp_startmoney, но сохранить старое значение и восстановить его позже. Повторно используем наш код mp_startmoney от раздела Получение кваров:

new g_oldmoney
 
SetStartMoney(newmoney)
{
	g_oldmoney = GetConVarInt(g_hStartMoney)
	SetConVarInt(g_hStartMoney, newmoney)
}
 
RestoreStartMoney()
{
	SetConVarInt(g_hStartMoney, g_oldmoney)
}

Although there are different functions for value types (float, string, et cetera), the internal data is always stored the same way. For example, this code will work:

public GetStartMoney()
{
	decl String:buffer[128]
 
	GetConVarString(g_hStartMoney, buffer, sizeof(buffer))
 
	return StringToInt(buffer)
}

Even though mp_startmoney is an integer, it can still be retrieved as a string.

Flags

ConVars can have a number of flags to change their behaviour. A few of the important flags are:

  • FCVAR_PROTECTED - Sensitive information (should not be exposed to clients or logs).
  • FCVAR_NOTIFY - Clients are notified of changes.
  • FCVAR_CHEAT - Can only be use if sv_cheats is 1.
  • FCVAR_REPLICATED - Setting is forced to clients.

Let's say we wanted to toggle whether a cvar had FCVAR_CHEAT. The following two functions could be used:

UnsetCheatVar(Handle:hndl)
{
	new flags = GetConVarFlags(hndl)
	flags &= ~FCVAR_CHEAT
	SetConVarFlags(hndl, flags)
}
 
SetCheatVar(Handle:hndl)
{
	new flags = GetConVarFlags(hndl)
	flags |= FCVAR_CHEAT
	SetConVarFlags(hndl, flags)
}

Change Callbacks

As of Half-Life 2, it is possible to know when ConVars change. While this is a very powerful feature, you must be careful not to set a ConVar inside a ConVar change hook such that it re-invokes he same callback. This results in infinite recursion.

For example, let's say you want to detect when bot_quota changes and to prevent it from going below 2:

new Handle:g_hBotQuota
 
public OnPluginStart()
{
	g_hBotQuota = FindConVar("bot_quota")
	if (g_hBotQuota != INVALID_HANDLE)
	{
		HookConVarChange(g_hBotQuota, OnBotQuotaChange)
	}
}
 
public OnBotQuotaChange(Handle:cvar, const String:oldVal[], const String:newVal[])
{
	if (StringToInt(newVal) < 2)
	{
		SetConVarInt(cvar, 2)
	}
}

Note 1: You do not need to explicitly unhook ConVarChange functions on shutdown. These hooks are removed when your plugin unloads.

Note 2: You cannot prevent cvar changes from happening; you can only change the value again. If the engine or game mod already have a change function installed for a ConVar, that function will always be called first.