X-script

From Esolang
(Redirected from X-Script)
Jump to navigation Jump to search

X-script is designed by PSTF.

Language Overview

X-Script is a Turing-complete, efficient, lightweight and concise programming language. It combines the simplicity of Python, the power of JavaScript, the "hacking" of assembly language, and the efficiency of C++.

Language History

  • X-script 1.0: PrySigneToFry created this language.
  • X-script 1.1: Added lambda expressions.
  • X-script 2.0: Added a lot of standard libraries.
  • X-script 2.½: Added repeat-until control flow.
  • X-script 2.1: Added register and added a comment for IDE.
  • X-script 2.2: Added constant.
  • X-script 2.3: Added Magic Constants.
  • X-script 3.0: Added stderr and self-interpret/self-evaluate.
  • X-script 3.0.1: Designed Win64 platform.
  • X-script 3.0.2: Subdivided table type.
  • X-script 3.0.3: Added HTML Library.
  • X-script 3.0.4: Fixed the method to parse a number or a boolean from a string, and parseInt() supports another base.

Basic Syntax Overview

Programming Mode

X-Script supports both imperative and scripted programming.

Imperative

The imperative mode just like you do Python in cmd.

X-Script 3.0.3 Line-V enviroment::2025-Jan-22, on Win64
> print("a")
a

> 

Scripted

X-Script scripted programming must program in X-IDE.[1]

The extension name of X-Script is ".xsc".

Comment

# I'm a one-line comment!
/**
 I am
 a multi-line
 comment!
 */

/**
 * Document comment
 * often used on
 * module/library document, 
 * just like in C++.
 */

/**
 /**
   It's illegal.
  */
 */

Identifier

X-Script uses every identifier that:

  1. Not started with number.
  2. Not include special symbols.
  3. Not keyword.

It is important to note that X-Script supports all kinds of Latin, Greek, Cyrillic, even Japanese, Chinese, Korean, and all left-to-right scripts, but not historical scripts, such as Rune, Gothic, cuneiform, or right-to-left scripts such as Arabic, Hebrew, Syriac, etc.

Thus, a, _i, my_name, PRYSIGNETOFRY, number_2, 我的名字, 私の名前, are legal identifier, and while, $money, 42dk are illegal identifier.

At the same time, we stipulate that if a variable starts with two underscores and is all uppercase, then the variable is protected by X-Script.

Variable

By default, all variables are global (unless you've declared them local) and can be accessed casually, even to a non-existent variable, without compilation errors or resulting in traceback output, but with a null value - None.

Of course, if you have declared its type, its value will be the default.

Use this code to define an variable:

var (var_type) var_name (= var_value)

Constants

Constants are the variable that unchangable.

Use this code to define a constant:

constant const (const_type) const_name = const_value

Magic constants

Magic constants are the constants that changes with special condition.

  1. __LINE__: Changes with current line number. Always unsigned number.
  2. __FILE__: Changes with file name. Always string.
  3. __DIRECTORY__: Changes with the path. Always string.
  4. __TIME__: Changes with the execution time. Always float number.

Data types

Currently, we have these types:

  • Numbers, such as 3, 7, 3.14, -2, 114514, 1e20, 3.683E-34, 3.130582375184619046479671967486, etc. Initial value is 0 for int, and 0.0 for float.
  • Strings, such as 'Hello' (or "Hello"). Strings can be enclosed in double quotes or single quotes, just like work in Python. Initial value is "". Use parseInt(), parseFloat() and parseLogic() to convert string to int, float or bool.
  • Booleans. It can only be True, or False. Initial value is False.
  • Tables. This is the most important data type in X-Script, it can express a list or a dictionary, such as {1, 2, 3}, or {key = value}. Initial value is {}. Also, if you define a table as a list, then you use brackets instead of braces.
    • List. It uses the brackets for table parentheses. initial value is []. You can use slice, as slice in Python.
    • Set. It is the common type of table, and it will sort when initialized, and sort after every deletion and insertion. Initial value is {}.
    • Dictionary. It is a table with key-value bind. Initial value is {}.
  • Tuples. It is just a "unchangable table", such as (5, 2), (4, 8, 3, 8, 9), but (1, ) instead of (1). Initial value is (,).
  • Functions. They're 1st-class citizens, which can be passed and returned as arguments.
  • Empty types. They has only a value, None. They converts to 0, but they can used to be true. When they converted to string, they becomes "啊?".
  • User-defined types. They're defined by "data" command.
  • Undefined behaviour. This often occurs when you trying to do something incorrect, such as 5/0. They converts to 0, but they can used to be false. When they converted to string, they becomes 99 bottles of beer.
  • Thread. It can fork a process out to do another program.

Special Assignment

X-Script also can assign many values to many variables.

When encountering an assignment statement, X-Script will evaluate all the values on the right before performing the assignment operation, so we can swap the values of the variables like this:

x = 6
y = 9
x, y = y, x

Index

X-Script uses subscript to index. However, -1 returns the first-to-last element, -2 is the second-to-last element, -3 is the third-to-last element, and so on.

Inputs and outputs

By default, X-Script outputs content to stdout and reads content from the stdin. You can specify the input and output files, and you can restore the handle by changing the file to "CON" (supposedly the Satanic username for Windows 98), outputting content to stdout and reading content from the stdin.

Use print() for output, and input() for input.

When the specified file does not exist, input() throws an error and print() automatically creates the file.

P.S.: input() normally returns a string.

Loop

X-Script supports five kinds of loops.

Loops
Loop type Description
for This is an iteration loop that executes a statement once for each iteration object in the iteration container (e.g., an element in a list, a number in a range array).
while It's a conditional loop that does the same thing over and over again when the condition is true. Before each execution, it checks whether the return value of the condition is true.
do ... while It's a conditional loop that does the same thing over and over again when the condition is true. After each execution, it checks whether the return value of the condition is true.
repeat ... until It's a conditional loop that does the same thing over and over again when the condition is true. After each execution, it checks whether the return value of the condition is false.
forever It's an endless loop where it does the same thing forever until it's broken.

You can control the loop by:

Loop control
Statement Description
break It will exit the loop immediately.
continue It will jump to the next round of the loop.

Conditional structure

X-Script uses the conditional jump just like Python, uses if-elif-else structure.

Functions

In X-Script, functions are the primary method of abstracting statements and expressions. It can be used to handle some special work, and it can also be used to calculate some values.

X-Script provides a number of built-in functions that you can easily call in your program, such as the print() function, which prints the parameters passed in to the console.

There are two main uses for X-Script functions:

  1. Complete the specified task, in which case the function is used as a call statement;
  2. Evaluates and returns a value, in which case the function is used as an expression for the assignment statement.

The definition format is shown as below:

optional_function_scope function return_value_type function_name(argument1, argument2, argument3..., argumentn)
    function_body
    (return result_params_comma_separated)
end

If you want to return nothing, you can omit the function type.

String

String can compare and do addition like string type in C++.

And, you can also put string in triple quote or sextuple quote, no escape needed because it becames a document string.

Error Handling

X-Script handles errors like in Python, but there is no ZeroDivisionError because it will causes an undefined behaviour.

OOP

X-Script is an Object-oriented programming language.

The definition of class

// Define a class and create an object
class Person:
    var name: string
    var age: int

    __init__(string name, int age):
        this.name = name
        this.age = age

    def greet() -> string:
        return f"Hello, my name is {this.name} and I am {this.age} years old."

var person = Person("Alice", 30) // "Spawn" a person
print(person.greet())  // Output: Hello, my name is Alice and I am 30 years old.

Inheritance and polymorphism

Let's say we've defined the person class.

class Employee: Person:
    var employeeId: string
 
    __init__(string name, int age, string employeeId):
        super(name, age)
        this.employeeId = employeeId
 
    override def greet() -> string:
        return super.greet() + " My employee ID is " + this.employeeId + "."
        // Adding two strings is equivalent to joining the following string to the tail of the previous string.
 
var employee = Employee("Bob", 40, "E12345")
print(employee.greet())  // Output: Hello, my name is Bob and I am 40 years old. My employee ID is E12345.

Garbage collection

X-Script will automatically collect garbages(dead objects, such as a variable that no longer to use).

Advanced Syntax Overview

Lambda Expressions

X-Script uses lambda to create an anonymous function.

The format of lambda expression is like this:

lambda *args: return_value

Here is an usage of lambda expression.

# A+B Problem
var f = lambda a, b: (a + b)
var int a = parseInt(input())
var int b = parseInt(input())
print(f(a, b))

Regular expressions

There is an library called re for regular expressions, just like work in Python.

Standard Libraries

Currently, X-Script supports these libraries:

math		random		re		os		sys		
internet	time		calendar	logo		cipher
matrix		kitten4		latex		graph		html

All of them are like works in Python/C++/R-Language/JS/Java/Haskell/…… , but except these changes:

  1. You can generate a negative-timestamp, or overflowed-timestamp, such as -639075600 means 1949 January 1st, 15:00:00.
  2. Logo includes exec_logo(script) function, directly uses FMSLogo syntax to program.
  3. Kitten4 can directly work by text, just when you open this page by English. Use double-brace({{...}}) for statement block.
  4. LaTeX library supports output as formatted SVG-file, and directly calculate value of expressions.
  5. Socket and Request are combined to Internet.
  6. The Cipher library supports a variety of encryption systems, including the most basic Caesar cipher, the Vigerene cipher, or the more advanced Base64 cipher, MD5, SHA, etc.

Register

The register keyword is used to hint to the compiler that the programmer wants to store a certain variable in the CPU's registers for quick access. However, there are a few things to keep in mind:

  • Hint: The register keyword is only a hint, not a forced command. The compiler can ignore this prompt and choose to store the variable in memory or elsewhere.
  • Optimization purpose: The purpose of using register is to optimize performance, especially in the case of frequent access to variables. Registers are accessed much faster than memory, so storing variables in registers can make your program run faster.
  • Limitations: Since register variables are stored in registers, they cannot get their addresses. Therefore, you cannot use the & operator on the register variable to get its address.

Self interpretions

There are two self-interpret functions:

  • eval()
  • exec()

eval() evaluates an expression, and return the value of the expression. exec() executes some codes, and return nothing.

They'll make Quine easier.

Output by stderr

In X-Script, you can also stream output by stderr. There are two types of output: error message output and debug information output.

Error message output(printerr)

  • Purpose: The printerr is mainly used to output error messages.
  • Characteristic:
    1. It is non-buffered, i.e. the output operation is performed immediately and there is no need to wait for the buffer to be full.
    2. It is often used for emergency error messages, as it can be displayed immediately in the terminal or in the error output device.
    3. By default, the printerr's output is directed to the standard error output (stderr).

Example:

var int a
var int b
a = parseInt(input())
b = parseInt(input())
if b == 0:
    printerr("The divisor cannot be 0!")
else:
    print(a / b)

Debug log output(printdebug)

  • Purpose: printdebug is mainly used to output log information or debugging information.
  • Characteristic:
    1. It is buffered, i.e., the output operation is performed deferred until the buffer is full or the buffer is explicitly flushed(you can flush the buffer by flush()).
    2. It is often used for non-urgent logging or debugging information, as it allows for more efficient output operations.
    3. The output of printdebug is also directed to the standard error output (stderr) by default, but unlike printerr, since it is buffered, multiple log messages can be merged to reduce the number of I/O operations.

Parse with other base

X-script supports parse string to integer with other base.

Example

var int x = parseInt(input(), base = 16)
print(char(x))

Input: 1F64B

Output: 🙋

Examples

They're collected in X-script/Examples.

Categories and References

  1. If you paste the code from any Internet explorer, then IDE will add one line to show its source to your script when you save it.