Skip to content

ObjectScript Reference

Evgeniy Golovin edited this page Mar 20, 2013 · 12 revisions

ObjectScript Reference

This section contains a complete reference of all built-in ObjectScript classes, modules, properies and functions.

Naming conventions for ObjectScript

For ObjectScript, it is conventional to use camelCase for properties and modules, PascalCase for classes, and ALL_CAPS for constants.

Classes and Modules

Class can be instantiated and has to be prototyped from Object or other class. Examples of classes: Regexp, String, Object and so on. If you want to create new class, do it like this

MyClass = extends Object {
	...
}

Module is singleton instance and has to be prototyped from _G or other module. Modules have not to be instantiated. Examples of modules: math, path and so on. If you want to create new module, do it like this

myModule = extends _G {
	...
}

Global functions

echo

void __echo__ ( ... )

Prints any number of arguments, using toString function to convert them to strings. This function is not intended for formatted output, but you of course can use string expressions (see Syntax of string expression).

var a = "!"
echo("Hello ", "World${a}") // outputs: Hello World!

print

void __print__ ( ... )

Prints any number of arguments, using toString function to convert them to strings. The print also prints "\t" between arguments, and "\n" when all arguments have printed. If no arguments passed then print does nothing. This function is not intended for formatted output actually, but only as a quick way to show a value, typically for debugging. For formatted output, use printf.

sprintf

string __sprintf__ ( string format, ... )

Returns a formatted string of its variable number of arguments following format string given in its first argument. The format string follows the same rules as the printf family of standard C functions.

A format specifier follows this prototype: %[flags][width][.precision][length]specifier

Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:

  • %v - default, depends on argument type
  • %s - string
  • %c - char (the first char of string)
  • %d, %i - integer, base 10
  • %o - integer, base 8
  • %b - integer, base 2
  • %x, %X - integer, base 16
  • %n - default number format, human friendly
  • %e - scientific notation, e.g. -1234.456e+78
  • %E - scientific notation, e.g. -1234.456E+78
  • %f - decimal point but no exponent, e.g. 123.456
  • %g - whichever of %e or %f produces more compact output
  • %G - whichever of %E or %f produces more compact output

The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications.

Flags:

  • - - Left-justify within the given field width; Right justification is the default (see width sub-specifier).
  • + - Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
  • (space) - If no sign is going to be written, a blank space is inserted before the value.
  • # - Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E, f, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
  • 0 - Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).

Width:

  • (number) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
  • * - The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Precision:

  • .(number) - For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E, f specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). The number can be negative to print rounded argument (see math.round function). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
  • .* - The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

The length sub-specifier modifies the length of the data type. This is a chart showing the types used to interpret the corresponding arguments with and without length specifier (if a different type is used, the proper type promotion or conversion is performed, if allowed).

printf

void __printf__ ( string fmt, ... )

Prints formatted string using sprintf to format arguments (see sprintf).

concat

string __concat__ ( ... )

Concatenates any number of arguments, using toString function to convert them to strings. Concatenation .. operator actually uses this function.

compileText

mixed __compileText__ ( string text, int source_code_type = SOURCECODE_AUTO, bool check_utf8_bom = true )

Compiles text and returns the compiled function. If there are errors then throws CompilerException.

If text contains one single function then compileText returns this function compiled, else ObjectScript wraps source code to function. The environment of the returned function is the global environment.

  • text - ObjectScript source code
  • source_code_type - type of ObjectScript file, if SOURCECODE_AUTO then the file type is detected automatically (it depends on file extension and content, it's generally recommended to use .os extension for ObjectScript files, and .osh for ObjectScript template files), if SOURCECODE_PLAIN then the file is parsed as normal ObjectScript file, if SOURCECODE_TEMPLATE then the file is parsed as template (ObjectScript parses a file, it looks for opening and closing tags, which are <% and %> which tell ObjectScript to start and stop interpreting the code between them. Parsing in this manner allows ObjectScript to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the ObjectScript parser, ObjectScript just outputs it. There are also special <%= and %> tags to output result of ObjectScript expression)
  • check_utf8_bom - if true then ObjectScript check utf-8 BOM bytes (it's especially useful for html templates, the utf-8 BOM bytes will not be outputed)

Usage examples

print(compileText("2+3")())						// outputs: 5
print(compileText("{|a, b| 3 + a*b}")(2, 3))	// outputs: 9

compileFile

mixed __compileFile__ ( string filename, int source_code_type = SOURCECODE_AUTO, bool check_utf8_bom = true )

Compiles file named filename and returns the compiled function. If there are errors then throws CompilerException. It's very similar to compileText function, but the compiled function returns _E by default.

eval

mixed __eval__ ( string text, ... )

Executes compiled text, could pass additional arguments calling the compiled function.

The eval is implemented in std.os

function eval(str){
	return compileText(str).apply(null, ...)
}

Usage examples

print(eval("2+3"))						// outputs: 5
print(eval("{|a, b| 3 + a*b}", 2, 3))	// outputs: 9

evalEnv

mixed __evalEnv__ ( string text, object env, ... )

Executes compiled text. It's similar to eval but calls the compiled function using env environment.

The evalEnv is implemented in std.os

function evalEnv(str, env){
	return compileText(str).applyEnv(env || _G, null, ...)
}

require

mixed __require__ ( string filename, bool required = false, int source_code_type = SOURCECODE_AUTO, bool check_utf8_bom = true )

Executes ObjectScript file.

  • filename - is name of file to be executed
  • required - if true then the file must be resolved else the require function throws exception, if false then the file either could be resolved or not
  • source_code_type - see compileText
  • check_utf8_bom - see compileText

The require function returns result of file executed.

The require function is implemented in core of ObjectScript

modulesLoaded = {}
function require(filename, required, source_code_type, check_utf8_bom){
	required === null && required = true
	var resolvedFilename = require.resolve(filename)
	if(!resolvedFilename){
		required && throw "required ${filename} is not found"
		return
	}
	filename = resolvedFilename
	return (modulesLoaded.getProperty(filename) || {||
		modulesLoaded[filename] = {} // block recursive require
		return modulesLoaded[filename] = compileFile(filename, required, source_code_type, check_utf8_bom)()
	}())
}

require.resolve

string __require.resolve__ ( string filename )

Resolves filename using require.paths array of valid paths.

typeOf

string __typeOf__ ( mixed val )

Returns name of val type

  • if null then returns "null"

  • if string then returns "string"

  • if number then returns "number"

  • if boolean then returns "boolean"

  • if array then returns "array"

  • if object then returns "object"

  • if userdata then returns "userdata"

    print(typeOf(null)) // outputs: null print(typeOf("123")) // outputs: string print(typeOf(123)) // outputs: number print(typeOf(false)) // outputs: boolean print(typeOf([1, 2, 3])) // outputs: array // outputs: object print(typeOf({firstname="Ivan", lastname="Petrov"}))

numberOf

mixed __numberOf__ ( mixed val )

Returns val as number if the val is primitive type, else it returns null.

See Convert to number.

toNumber

mixed __toNumber__ ( mixed val )

Converts val to number if the val is primitive types, else it calls valueOf method and converts result to number (the valueOf must return value of a primitive type).

See Convert to number.

stringOf

mixed __stringOf__ ( mixed val )

Returns val as string if the val is primitive type, else it returns null.

See Convert to string.

toString

mixed __toString__ ( mixed val )

Converts val to string if the val is primitive type, else it calls valueOf method and converts result to string (the valueOf must return value of a primitive type).

See Convert to string.

arrayOf

mixed __arrayOf__ ( mixed val )

Returns val if the val is array, else it returns null.

toArray

mixed __toArray__ ( mixed val )

Returns val converted to array or null if the val is null.

The toArray is implemented in std.os

function toArray(a){
	arrayOf(a) && return a;
	var type = typeOf(a)
	if(type == "object"){
		var arr = []
		for(var i, v in a){
			arr.push(v)
		}
		return arr
	}
	if(type == "null"){
		return null
	}
	return [a]
}

objectOf

mixed __objectOf__ ( mixed val )

Returns val if the val is object, else it returns null.

toObject

mixed __toObject__ ( mixed val )

Returns val converted to object or null if the val is null.

The toObject is implemented in std.os

function toObject(a){
	objectOf(a) && return a;
	var type = typeOf(a)
	if(type == "array"){
		var object = {}
		for(var i, v in a){
			object.push(v)
		}
		return object
	}
	if(type == "null"){
		return null
	}
	return {a}
}

userdataOf

mixed __userdataOf__ ( mixed val )

Returns val if the val is userdata, else it returns null.

functionOf

mixed __functionOf__ ( mixed val )

Returns val if the val is function, else it returns null.

toBool

boolean __toBool__ ( mixed val )

Converts val to boolean.

Beware that ObjectScript considers both zero and the empty string as true in conditional tests.

print(null ? true : false)	// outputs: false
print(1 > 2 ? true : false)	// outputs: false
print(1 ? true : false)		// outputs: true
print(0 ? true : false)		// outputs: true
print("0" ? true : false)	// outputs: true
print("" ? true : false)	// outputs: true
print([1,2] ? true : false)	// outputs: true

Note: !! operator is identical to the toBool function

var val = 12
print(!!val === toBool(val)) // outputs: true

debugBackTrace

terminate

unhandledException

Regexp

SqliteConnection

Curl

GC

process

math

path

File

Buffer

Exception

Object

String

Array

Function

Number

Boolean

Userdata

Resources

Clone this wiki locally