DM Guide 17

Материал из Chaotic Onyx
Версия от 23:18, 17 апреля 2015; Eversor (обсуждение | вклад) (Продолжаю переводить)
(разн.) ← Предыдущая версия | Текущая версия (разн.) | Следующая версия → (разн.)
Перейти к навигацииПерейти к поиску

Это 17-ая глава перевода оригинального руководства по Dream Maker от разработчиков.

Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.

Оригинальная 17-ая глава руководства на английском языке

В разработке…


Jobeng.png
Данная статья помечена как неоконченная. Это означает, что статья находится на доработке, поэтому может быть неверна или неактуальна.

Вы можете помочь проекту Onyxyeye@256x256.png Onyx и сообществу Animus-logo.png SS13 в целом — зайдите на наш Bus Mainframes.gif Портал сообщества.
Также вы можете прочитать эту статью на ["[1]" зарубежном вики-проекте].


Глава 17: Контроль сервера и системы

All creatures pass into My nature at the end of a cycle and are reborn at the beginning of creation.

--Bhagavat Gita

Все ранее рассмотренные аспекты DM представляли собой операции, выполняемые в изолированной области игрового мира. В этой главе рассматриваются команды, позволяющие взаимодействовать с остальной частью компьютера, включая доступ к файлам, программам и другим мирам BYOND’а.

Замечание о платформо-независимости

Программисты называют платформой операционную систему, запущенную на компьютере. На данный момент, BYOND может быть запущен на операционных системах Microsoft Windows и UNIX. Версии для других ОС находятся в разработке.

Когда возможно, лучше писать т.н. платформо-независимые программы, это означает, что программа будет работать одинаково на разных системах. Язык DM практически гарантирует это, предоставляя синтаксис, как можно меньше опирающийся на особенности внешней вычислительной среды. Фактически, BYOND во многих случая ведет себя как виртуальная операционная система, изолируя ваш код от реальной операционной системы, и тем самым обеспечивает одинаковую среду независимо от машины, на которой он запущен.

Однако когда возникает задача получения доступа к файлам или другим программам компьютера, зависимость от платформы становится необходимой. Например, названия файлов в UNIX регистрозависимы, в то время как в Windows наоборот. Это означает, что при указании имени файла в Windows вы можете обойтись любой комбинацией строчных и прописных букв, в то время как тот же код, запущенный под UNIX сработает только при полном совпадении регистра в имени файла. Поэтому хорошей привычкой будет, по крайней мере, быть последовательным и использовать одинаковый регистр во всем вашем коде, когда ссылаешься на один файл.

Пути к фалам соответствуют текущей директории (если не задан полный путь). Текущей всегда является директория, в которой расположен .dmb файл мира. В UNIX системах в пути после каждой поддиректории ставится знак / . Обычно в Windows для этой цели используется знак \ , однако, DM позволяет использовать вместо него / . Это удобнее, потому, что так он не рассматривается как спецсимвол в текстовой строке.

shell

shell передает команду операционной системе. Интерпретатор команд часто называют shell - отсюда и название для этой инструкции. Это спящая операция, которая возвращает значение после ее окончания.

shell (Cmd)
Cmd – текст команды.
Возвращает статус завершения команды Returns the exit status of the command.

Синтаксис команды, очевидно, полностью зависит от операционной системы. Как правило, она состоит из имени программы и следующего за ним ряда аргументов. Если команда создает вывод (output) или ожидает ввода (input), вам нужно перенаправить ввод и вывод в файлы, что в UNIX и Windows делается при помощи операторов < и > .

В нижеследующем примере запускается команда "dir" и выводится результат.

mob/verb/list_files()
   shell("dir > dir.txt")
   usr << browse("dir.txt")

Операции с файлами

file2text

file2text считывает файл в текстовую строку. Может быть использована в разных целях, включая доступ к выводу команды shell().

file2text (File)
File – имя файла.
Возвращает содержимое файла в виде текстовой строки.

text2file

text2file instruction is the complement of file2text. It appends a text string to a file. If the file does not exist, it will be created.

text2file (Txt,File)
Txt is the text string.
File is the file to append to.

file

file instruction returns a reference to a file object. The primary use for such an object is with the input/output operators. Outputting a file to a player was discussed in section 11.2.7. It is also possible to send output to a file or get input from a file.

file (Path)
Path is the name of the file.
Returns a reference to the file.

Using a file as the target for output of the << operator has the same effect as calling text2file(). The output value is appended to the file. Similarly, reading input from a file with the >> operator is the same as file2text(). The file is loaded into a text string and stored in the specified variable.

File << Output
File >> Variable

fcopy

fcopy instruction copies one file to another. The source file may be a real external file or a file in the cache. If the destination file already exists, it will be replaced.

fcopy (Source,Dest)
Source is the source file.
Dest is the destination file.
Returns 1 on success and 0 on failure.

fdel

fdel instruction deletes a file from the file system.

fdel (File)
File is the name of the file.
Returns 1 on success and 0 on failure.

It works with entire directories too (so be careful for heaven's sake). As a precaution, it only accepts directory names when you end them with a slash "/".

flist

flist instruction generates a list of files at the specified path in the file system and whose names begin in the specified way.

flist (Path)
Path is the path to get the listing of.
Returns a list of files and sub-directories.

Only files and sub-directories directly contained in the specified path are listed (i.e. not the contents of the sub-directories too). The file names in the list do not contain the path information but just the bare file name. Sub-directories in the list are identified by a trailing "/" appended to the name.

The format of the path is "dir1/dir2/.../file". Only files matching "file" are listed, so be sure to append a "/" to the end of a directory name if you wish to see its contents. Otherwise, all you will get is the directory name back with a "/" appended.

Running other Worlds

It is sometimes desirable for one master world to launch child worlds. For example, you might have a main world with side-adventures (dungeons etc.) taking place in separate sub-worlds. This might be more efficient since areas that are rarely used could be activated only when needed.

The ultimate use of this technique is a world hosting service which allows users to upload their own world files. These are then launched and shut down as they are accessed by players. If you do not have your own dedicated network connection, you may wish to make use of such a service to host your worlds.

startup

startup instruction runs another world. It sleeps until the network address of the new world has been determined.

startup (File,Port=0,Options,...)
File is the dmb file to run.
Port is the network port to use.
Options includes any additional parameters.
Returns network address of the new world.

The network address of a world includes two parts. The first is the IP address of the machine it is running on. The second is the port number. These are combined in a text string of the form "ip:port". The port specified must not be in use by any other programs. The default value of zero indicates that any available port should be used.

The additional options that may be specified are described in the following list.

  • -once This option automatically shuts down the server when all players have logged off.
  • -log This option takes an additional argument which is used as the server's output file. All debugging notices (from proc crashes) and any output sent to world.log is appended to this file. The path to the file is relative to the new server's working directory, which is the location of the .dmb file.
  • -safe This option runs the world in a special protective security mode. The world code may only access files in the same directory (or below) as the .dmb file and access to the shell instruction is disabled. This is the default mode if the world is run from its own safe directory. Such a directory is recognized when it has the same name as the world .dmb file (напр. inferno/inferno.dmb).
  • -ultrasafe This is the same as -safe except only access to temporary files is allowed. This is the default if the world is not run from its own safe directory.
  • -trusted In this mode, all operations are permitted. The world may access files in any directory and may run shell commands. Of course the operating system may apply restrictions, but BYOND will allow the world to try anything.
  • -params The following argument is interpreted as a parameter string as described in [DM_Guide_10|section]. The variable world.params is initialized from this data. You may use params multiple times; the individual parameter strings are simply concatenated to form the final result.
  • -quiet This simply disables informational output that the server normally displays when it boots up.

Control over Child Worlds

Communication with a child world may be done through world.Export(). In this case, the child world's world.Topic() procedure is called with a special master flag to indicate that the message came from the world which started it. (See [DM_Guide_8|section] for a review of these procs.) By default, a child world will respond to the special topics "Del" and "Reboot" by calling world.Del() and world.Reboot() respectively. This is only done if the message comes from the master world, since otherwise anyone could send the message and shut your world down. Another useful topic is "ping", which can be used to determine if a child world is still alive and running.

shutdown

shutdown instruction may be used to close a child world or to wait for it to exit normally.

shutdown (Address,Natural=0)
Address is the network address of the world.
Natural is 1 to suppress sending of "Del" message.
Returns exit status of the child world.

The address should be the same text string returned by startup(). If the second argument is omitted or zero, this is equivalent to calling world.Export() with the given address and "Del" as the topic. Otherwise, this instruction simply waits for the child world to die naturally of its own accord.

With no arguments at all, this instruction causes the current world to shut down. The same thing can be achieved by calling world.Del().