NT Script

Материал из Tau Ceti Station Wiki
Перейти к навигации Перейти к поиску

Это старая страница, оставленная как память о былых временах.
Статья помещена в категорию Старые страницы.
Информация на этой странице может оказаться не актуальной, устаревшей.

The NT Scripting Language(NT Script, or NTSL) это новая технология продвигаемая Департаментом технологий НТ для того чтобы стандартизировать программирование всех электронных устройств Нанотрейзен. Его синтакс это смесь PHP, C++, и JavaScript. Большинство реализаций NT Script не объектно-ориентированные и не допускают различия классов,но используют систему памяти ROBUST(tm) чтобы сохранят информацию в виде динамического дерева. NT Script does allow the in-line definition of functions, however.

It is important to note that NT Scripting should not be treated as BYOND coding. NT Scripting handles some things differently than BYOND does.

Syntax Guide

NT Script следует простому в использовании синтаксису разработанномуй для пользователей всех уровней программирования. Пробелы игнорируются, точки с запятой и фигурные скобки обязательны.


Переменные

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

myVariable = 5;
	

Кроме того, можно присвоить той же переменной текстовое значение или строку.

myVariable = "Hello world!";

Функции

Функции могут быть использованы и определены динамически. Существуют различные заранее определенные функции для NTSL реализации, Но основные из них будут оставаться такими же . Вот как вы можете использовать функцию:


myVariable = getNumber();

В этом примерe, переменной myVariable присваивающееся значение возвращаемое getNumber(). Каждая функция возвращает значение, даже если оно не определено. Вот несколько примеров использования функции:

print(myVariable);
print("Hello world!");
print("Griffing assistants in T-minus " + myVariable + " seconds.");


Вы также можете определить вашу собственную функцию, используя def.

def getNumber() {
    return 5;
}

Блоки кода

Блоки кода объявляются когда конкретный кусок кода сигнализирует о объявление блока кода. Переменные определенные в одном блоке кода не могут применены или изменены в других не связанных блоках кода; это известно как область. Например:

myGlobalVariable = getNumber();

while(myGlobalVariable != 0) {
    
   myLocalVariable = 0;
   myGlobalVariable = myLocalVariable;
}

myLocalVariable = 50; // это неправильно; myLocalVariable не существует в этой области

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

Условные операторы

The while() loop in the previous example is considered a conditional because it only continues executing when the condition between the parentheses is true. The != is known as a relational operator which returns true to the interpreter if myGlobalVariable does not equal 0. It can be read as "while myGlobalVariable does not equal 0, execute the following block of code".

Here is a list of all relational operators:


== : Равно
!=  : Не равно
<  : Меньше
>  : Больше
<= : Меньше или равно
>= : Больше или равно


Relational operators can be used in if() statements, which are used the following way:

if(myVariableNumber == 50) {
   // code block
}
else {   // the relational operator was not met
   // code block
}

NT Deluxe Namespaces

Nanotrasen will constantly add new universal functions and features to NTSL, here are a few of them:


Vector Namespace

Vectors are resizeable data containers for storing any form of entities inside. They are very useful for serving as lists; their members can be instantly accessed provided you have an appropriate position.

vector()

vector(entry1, entry2, ...)

Returns a vector with a given number of entities. You can add an infinite number of entries, or no entries at all.

at()

at(vector, position, value)

The NTSL-equivalent of array[index]. A NTSL vector starts at index 1. As the language develops, this will most likely be offloaded to the [] operator.

copy()

copy(vector, start, end)

Returns a new vector with only the contents of the specified vector at the start position and end position.

push_back()

push_back(vector, entry1, entry2, ...)

Adds specified entries to the specified vector. Note: the +=operator overloads this function, and can be used as so:

vector += myName;

remove()

remove(vector, entry1, entry2, ...)

Removes specified entries from the specified vector.

cut()

cut(vector, start, end)

Cuts out entries from start to end in the specified vector.

swap()

swap(vector, index1, index2)

Swaps the entities at index1 and index2 in the specified vector.

insert()

insert(vector, index, entry)

Inserts an entry into the specified position.


Miscellaneous Definitions

pick()

pick(entry1, entry2, entry3, ...)

Returns a randomly-selected entry from the parameters. Note: vector parameters will add their entries into the "raffle". The function will never return a vector.

find()

find(container, element)

Searches a vector or string for this element or substring. Returns nonzero if found.

prob()

prob(chance)

Returns nonzero is the probability succeeded. Returns zero if the probability failed.

length()

length(container)

Finds the length of a string or vector.

substr()

substr(string, start, end)

Returns a string/text copied from the specified string, from start to end.


Prefab Variables

PI = 3.141592653;
E = 2.718281828;
SQURT2 = 1.414213562;
FALSE = 0; // true/false are just Boolean shortcuts to 0 and 1
TRUE = 1;
NORTH/SOUTH/EAST/WEST = direction; // can be any cardinal direction



(UNDER CONSTRUCTION)

Traffic Control Systems Implementation

The Telecommunications system is directly tied to the TCS scripting implementation. It comes with the following functions and features.


Realtime signal modification

If the code is set to execute automatically, signals will first execute stored server code. Signal information is stored in the following variables:

$source  // the source of the signal
$content // the content of the signal
$freq    // the frequency of the signal
$pass    // determines if the signal will be broadcasted
$job     // the job (only for radio messages) of the orator


Functions

TCS also comes with the following functions (parameters may be ignored for automatic assignment):


broadcast()

broadcast(message, frequency, source, job)

Sends a radio signal to neighboring subspace broadcasters to broadcast with the following parameters.

message: The radio message
frequency: The frequency to broadcast to
source: The name of the broadcaster. If the source name is not in a server-side voice databank (voice analysis is performed every time a person speaks over a channel) the name will appear in UPPERCASE and Italicized to indicate a synthesized voice job
job: The job of the orator.

Examples:

broadcast("Hello world!");

defaults:
frequency: 1459
source: the server name
job: None


broadcast("HELP GRIEFF", 1459, "Burer", "Security Officer");


mem()

mem(address, value)

Either returns a value if value is not specified, or sets the value of the memory address

address: The memory address to search or apply to
value: The value to apply to the address. Can be any form of data

Examples:

mem($source + "'s Mom");


mem($source + "'s Mom", "Lindsay Donk");