1.16. 内置函数

1.16.1. 全局符号

array(size[, fill])

创建并返回指定大小的数组。如果指定了可选参数 fill,则其值将用于填充新数组的插槽。如果省略 fill 参数,则改用 null。

callee()

返回当前正在运行的 Closure

getroottable()

返回 VM 的根表。

getconsttable()

返回 VM 的 const 表。

assert(exp[, message])

如果 exp 为 null 或 false,则引发异常。默认情况下,引发 “assertion failed” 字符串,如果指定,则引发 message。 如果 message 参数是 function,则对其进行评估,并将返回值用作消息文本。这是为了避免在不需要时进行不必要的字符串格式化。

print(x)

打印 x 调用主机应用程序打印函数由 (sq_setprintfunc) 调用

println(x)

打印 x 向结果字符串添加换行符 (’n’)

error(x)

打印 x 调用主机应用程序错误打印由 (sq_setprintfunc) 调用设置的函数

errorln(x)

与 error(x) 相同,但将换行符 (’n’) 添加到结果字符串中

compilestring(string[, buffername][, bindings])

将包含 Quirrel 脚本的字符串编译为函数并返回它:

let compiledscript=compilestring("println(\"ciao\")")
//运行脚本
compiledscript()

或提供编译时绑定:

let api = {function foo() {println("foo() called")}}
let compiledscript=compilestring("foo()", "bindings_test", api)
compiledscript()
type(obj)

返回对象的 ‘raw’ 类型,而不调用元方法 ‘_typeof’。

newthread(threadfunc)

创建一个新的 Cooperative Thread 对象 (Coroutine) 并返回它

freeze(x)

返回对给定对象的不可变引用。 如果参数是 POD 类型,则引发错误(以帮助防止错误)。

call_type_method(object, <method_name>[, ...])

调用对象的内置类型方法,参数位于变量参数中,例如:

call_type_method({foo=1}, “findvalue”, @(v) v==1) //1

getobjflags(x)

给定对象 handle 时,返回其标志,这些标志可能是:

  • 0 - 无特殊标志

  • SQOBJ_FLAG_IMMUTABLE - 如果对象句柄是不可变的,则设置位

1.16.1.1. 默认委托

除了 null 和 userdata 之外,每个 quirrel 对象都有一个默认委托,其中包含一组函数,用于从对象本身作和检索信息。 所有这些默认委托也可以通过在委托名称前添加 $ 符号来调用,如 table.$tostring()table?.$tostring()。 使用 ‘$’ 符号,Squirrel 将知道您要调用 default delegate。这在表和实例中非常重要 ({len=@() 0}.len() //0{len= @() 0}.$len() //1)

1.16.2. Integer

integer.tofloat()

将数字转换为 float 并返回

integer.tostring()

将数字转换为字符串并返回

integer.tointeger()

虚拟函数;返回 Integer 的值。

integer.tochar()

返回一个字符串,其中包含由整数表示的单个字符。

integer.weakref()

虚拟函数;返回整数本身。

1.16.3. Float

float.tofloat()

返回 float(dummy function) 的值

float.tointeger()

将数字转换为整数并返回

float.tostring()

将数字转换为字符串并返回

float.tochar()

返回一个字符串,其中包含由 float 的 Integer 部分表示的单个字符。

float.weakref()

虚拟函数;返回浮点数本身。

1.16.4. Bool

bool.tofloat()

returns 1.0 for true 0.0 for false

bool.tointeger()

returns 1 for true 0 for false

bool.tostring()

returns “true” for true and “false” for false

bool.weakref()

dummy function; returns the bool itself.

1.16.5. String

string.len()

returns the string length

string.tointeger([base])

Converts the string to integer and returns it. An optional parameter base can be specified–if a base is not specified, it defaults to base 10.

string.tofloat()

converts the string to float and returns it

string.tostring()

returns the string (really, a dummy function)

string.slice(start[, end])

returns a section of the string as new string. Copies from start to the end (not included). If start is negative the index is calculated as length + start, if end is negative the index is calculated as length + end. If end is omitted end is equal to the string length.

string.indexof(substr[, startidx])

Searches for a sub string (substr) starting from the index startidx and returns the position of its first occurrence. If startidx is omitted the search operation starts from the beginning of the string. The function returns null if substr is not found.

string.contains(substr[, startidx])

Checks if the string contains a sub string (substr) anywhere starting from the index startidx. Returns boolean value.

string.tolower()

returns a lowercase copy of the string.

string.toupper()

returns a uppercase copy of the string.

string.weakref()

returns a weak reference to the object.

string.subst(...)

This delegate is used to format strings. A format string can contain variable positional arguments and table keys. As parameters, you can pass an arbitrary number of tables and arbitrary number of positional arguments. If the key is found in several tables, then the most value from the leftmost table will be used.

Example:

"Score: {0}".subst(4200) => "Score: 4200"
"x={0} y={1} z={2}".subst(42, 45.53, -10.8) => "x=42 y=45.53 z=-10.8"
"Score: {score}".subst({score=4200}) => "Score: 4200"
"x={x} y={y} z={z}".subst({y=45.53, x=42, z=-10.8}) => "x=42 y=45.53 z=-10.8"
"Type: {type}, Health: {hp}".subst({hp=100, damage=5}, {isAir=true, type="helicopter"}) => "Type: helicopter, Health: 100"
"Type: {type}, Pos: x={0} y={1} z={2}".subst({isAir=true, type="helicopter"}, 42, 45.53, -10.8) => "Type: helicopter, Pos: x=42 y=45.53 z=-10.8"
"Score: {0}".subst() => "Score: {0}"
"Score: {score}".subst({}) => "Score: {score}"
string.replace(from, to)

Replaces all occurrences of ‘from’ substring to ‘to’

string.join(arr[, filter])

Concatenate all items in provided array using string itself as separator. Example: :: “, “.join([“a”, “b”, “c”]) // => “a, b, c”

Optional filter parameter can be specified. When it is set to true (boolean), default filter is used which keeps items which are non-null and not “” (empty string). When filter is a function, it is called for every item and must return true for elements that should be included in resulting string. Example: :: “, “.join([“a”, null, “b”, “”, “”, “c”], true) // => “a, b, c” “, “.join([“a”, null, “b”, “”, “”, “c”], @(v) v!=null)) // => “a, b, , , c”

string.concat(...)

Concatenate all arguments using string itself as separator. Example: :: “, “.concat(“a”, “b”, “c”) // => “a, b, c”

string.split([sep])

Return a list of the words in the string, using sep as the delimiter string. If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, ‘1,,2’.split(‘,’) returns [‘1’, ‘’, ‘2’]). The sep argument may consist of multiple characters (for example, ‘1<>2<>3’.split(‘<>’) returns [‘1’, ‘2’, ‘3’]). Splitting an empty string with a specified separator returns [‘’].

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace without providing a separator returns [].

string.split_by_chars(separators[, skipempty])

returns an array of strings split at each point where a separator character occurs in str. The separator is not returned as part of any array element. The parameter separators is a string that specifies the characters as to be used for the splitting. The parameter skipempty is a boolean (default false). If skipempty is true, empty strings are not added to array.

eg.
let a = "1.2-3;;4/5".split_by_chars(".-/;")
// the result will be  [1,2,3,,4,5]
or
let b = "1.2-3;;4/5".split_by_chars(,".-/;",true)
// the result will be  [1,2,3,4,5]
string.hash()

Returns integer hash value of a string. It is always non-negative (so it doesn’t always match Quirrel string internal hash value).

string.lstrip()

Strips white-space-only characters that might appear at the beginning of the given string and returns the new stripped string.

string.rstrip()

Strips white-space-only characters that might appear at the end of the given string and returns the new stripped string.

string.strip()

Strips white-space-only characters that might appear at the beginning or end of the given string and returns the new stripped string.

string.startswith(cmp)

returns true if the beginning of the string str matches the string cmp; otherwise returns false

1.16.6. Table

table.len()

Returns the number of slots contained in a table

table.rawget(key)

Tries to get a value from the slot ‘key’ without employing delegation

table.rawset(key, val)

Sets the slot ‘key’ with the value ‘val’ without employing delegation. If the slot does not exists, it will be created. Returns table itself.

table.rawdelete(key)

Deletes the slot key without employing delegation and returns its value. If the slot does not exists, returns null.

table.rawin(key)

Returns true if the slot ‘key’ exists. the function has the same effect as the operator ‘in’ but does not employ delegation.

table.weakref()

Returns a weak reference to the object.

table.tostring()

Tries to invoke the _tostring metamethod. If that fails, it returns “(table : pointer)”.

table.clear()

Removes all the slots from the table. Returns table itself.

table.filter(func(val, [key], [table_ref]))

Creates a new table with all values that pass the test implemented by the provided function. In detail, it creates a new table, invokes the specified function for each key-value pair in the original table; if the function returns ‘true’, then the value is added to the newly created table at the same key.

table.keys()

Returns an array containing all the keys of the table slots.

table.values()

Returns an array containing all the values of the table slots.

table.topairs()

Returns an array containing arrays of pairs [key, value]. Useful when you need to sort data from table.

table.clone()

Returns a clone of table.

table.map(func(slot_value, [slot_key], [table_ref]))

Creates a new table of the same size. For each element in the original table invokes the function ‘func’ and assigns the return value of the function to the corresponding slot of the newly created table. Provided func can accept up to 3 arguments: slot value (required), slot key in table (optional), reference to table itself (optional). If callback func throws null, the element is skipped and not added to destination table.

table.each(func(slot_value, [slot_key], [table_ref]))

Iterates a table and calls provided function for each element.

table.findindex(func(slot_value, [slot_key], [table_ref]))

Performs a linear search calling provided function for each value in the table. Returns the index of the value if it was found (callback returned true (non-false) value) or null otherwise.

table.findvalue(func(slot_value, [slot_key], [table_ref]), [def=null])

Performs a linear search calling provided function for each value in the table. Returns matched value (for which callback returned non-false value) or default value otherwise (null if not provided).

table.reduce(func(accumulator, slot_value, [slot_key], [table_ref]), [initializer])

Reduces a table to a single value (similar to array.reduce()). For each table slot invokes the function ‘func’ passing the initial value (or value from the previous callback call) and the value of the current element. Callback function can also take optional parameters: key in table for current value and reference to table itself. Iteration order is not determined.

table.__merge(table_1, [table_2, ][table_3, ]...)

This delegate is used to create new table from old and given. Arguments to merge fields from can be tables, classes and instances.

table.getfuncinfos()

If table has a delegate with _call() metamethod, get info about it (see function.getfuncinfos() for details).

Example:

let foo = {fizz=1}
let bar = foo.__merge({buzz=2})
=> foo == {fizz=1}; bar={fizz=1, buzz=2}
table.__update(table_1, [table_2, ][table_3, ]...)

This delegate is used to update new table with values from given ones. In other words it mutates table with data from provided tables.

Example:

let foo = {fizz=1}
let bar = foo.__update({buzz=2})
=> foo == {fizz=1, bazz=2}; bar={fizz=1, buzz=2}
table.is_frozen()

Return true if reference to the table is frozen with ‘freeze’ global function.

1.16.7. Array

array.len()

returns the length of the array

array.append(val, [val_2, ][val_3, ]...)

sequentially appends the values of arguments ‘val’ to the end of the array. Returns array itself.

array.extend(array_1, [array_2, ][array_3, ]...)

Extends the array by appending all the items in all the arrays passed as arguments. Returns target array itself.

array.pop()

removes a value from the back of the array and returns it.

array.top()

returns the value of the array with the higher index

array.insert(idx, val)

inserts the value ‘val’ at the position ‘idx’ in the array. Returns array itself.

array.remove(idx)

removes the value at the position ‘idx’ in the array and returns its value.

array.resize(size[, fill])

Resizes the array. If the optional parameter ‘fill’ is specified, its value will be used to fill the new array’s slots when the size specified is bigger than the previous size. If the fill parameter is omitted, null is used instead. Returns array itself.

array.sort([compare_func])

Sorts the array in-place. A custom compare function can be optionally passed. The function prototype as to be the following.:

function custom_compare(a,b) {
    if(a>b) return 1
    else if(a<b) return -1
    return 0;
}

a more compact version of a custom compare can be written using a lambda expression and the operator <=>

arr.sort(@(a,b) a <=> b);

Returns array itself.

array.reverse()

reverse the elements of the array in place. Returns array itself.

array.slice(start[, end])

Returns a section of the array as new array. Copies from start to the end (not included). If start is negative the index is calculated as length + start, if end is negative the index is calculated as length + end. If end is omitted end is equal to the array length.

array.weakref()

returns a weak reference to the object.

array.tostring()

returns the string “(array : pointer)”.

array.totable()

Creates a table from arrays containing arrays of pairs [key,value]. Reverse of table.topairs().

array.clear()

removes all the items from the array

array.map(func(item_value, [item_index], [array_ref]))

Creates a new array of the same size. For each element in the original array invokes the function ‘func’ and assigns the return value of the function to the corresponding element of the newly created array. Provided func can accept up to 3 arguments: array item value (required), array item index (optional), reference to array itself (optional). If callback func throws null, the element is skipped and not added to destination array.

array.apply(func([item_value, [item_index], [array_ref]))

for each element in the array invokes the function ‘func’ and replace the original value of the element with the return value of the function.

array.each(func(item_value, [item_index], [array_ref]))

Iterates an array and calls provided function for each element.

array.reduce(func(prevval,curval,[index],[array_ref]), [initializer])

Reduces an array to a single value. For each element in the array invokes the function ‘func’ passing the initial value (or value from the previous callback call) and the value of the current element. Callback can optionally accept index of current value and reference to array itself. The return value of the function is then used as ‘prevval’ for the next element. If the optional initializer is present, it is placed before the items of the array in the calculation, and serves as a default when the sequence is empty. If initializer is not given then for sequence contains only one item, reduce() returns the first item, and for empty sequence returns null.

Given an sequence with 2 or more elements (including initializer) calls the function with the first two elements as the parameters, gets that result, then calls the function with that result and the third element, gets that result, calls the function with that result and the fourth parameter and so on until all element have been processed. Finally, returns the return value of the last invocation of func.

array.filter(func(val, [index], [array_ref]))

Creates a new array with all elements that pass the test implemented by the provided function. In detail, it creates a new array, for each element in the original array invokes the specified function passing the index of the element and it’s value; if the function returns ‘true’, then the value of the corresponding element is added on the newly created array.

array.indexof(value)

Performs a linear search for the value in the array. Returns the index of the value if it was found null otherwise.

array.contains(value)

Performs a linear search for the value in the array. Returns true if it was found and false otherwise.

array.findindex(func(item_value, [item_index], [array_ref]))

Performs a linear search calling provided function for each value in the array. Returns the index of the value if it was found (callback returned true (non-false) value) or null otherwise.

array.findvalue(func(item_value, [item_index], [array_ref]), [def=null])

Performs a linear search calling provided function for each value in the array. Returns matched value (for which callback returned non-false value) or default value otherwise (null if not provided).

array.replace(source_arr)

Copies content of source array into given array by replacing its contents. Returns target array itself.

array.is_frozen()

Return true if reference to the array is frozen with ‘freeze’ global function.

array.clone()

Return clone of the array.

1.16.8. Function

function.call(_this, args...)

calls the function with the specified environment object(‘this’) and parameters

function.pcall(_this, args...)

calls the function with the specified environment object(‘this’) and parameters, this function will not invoke the error callback in case of failure(pcall stays for ‘protected call’)

function.acall(array_args)

calls the function with the specified environment object(‘this’) and parameters. The function accepts an array containing the parameters that will be passed to the called function.Where array_args has to contain the required ‘this’ object at the [0] position.

function.pacall(array_args)

calls the function with the specified environment object(‘this’) and parameters. The function accepts an array containing the parameters that will be passed to the called function.Where array_args has to contain the required ‘this’ object at the [0] position. This function will not invoke the error callback in case of failure(pacall stays for ‘protected array call’)

function.weakref()

returns a weak reference to the object.

function.tostring()

returns the string “(closure : pointer)”.

function.bindenv(env)

clones the function(aka closure) and bind the environment object to it(table,class or instance). the this parameter of the newly create function will always be set to env. Note that the created function holds a weak reference to its environment object so cannot be used to control its lifetime.

function.getfuncinfos()

returns a table containing informations about the function, like parameters, name and source name;

//the data is returned as a table is in form
//pure quirrel function
{
  native = false
  name = "zefuncname"
  src = "/somthing/something.nut"
  parameters = ["a","b","c"]
  defparams = [1,"def"]
  varargs = 2
  freevars = 0
}
//native C function
{
  native = true
  name = "zefuncname"
  paramscheck = 2
  typecheck = [83886082,83886384] //this is the typemask (see C defines OT_INTEGER,OT_FLOAT etc...)
  freevars = 2
}
function.getfreevar(idx)
returns a table containing information about given free variable ::

{ name=”foo”, value=5 }

1.16.9. Class

class.instance()

returns a new instance of the class. this function does not invoke the instance constructor. The constructor must be explicitly called (eg. class_inst.constructor(class_inst) ).

class.rawin(key)

returns true if the slot ‘key’ exists. the function has the same effect as the operator ‘in’ but does not employ delegation.

class.weakref()

returns a weak reference to the object.

class.tostring()

returns the string “(class : pointer)”.

class.rawget(key)

tries to get a value from the slot ‘key’ without employing delegation

class.rawset(key, val)

sets the slot ‘key’ with the value ‘val’ without employing delegation. If the slot does not exists, it will be created.

class.newmember(key, val[, bstatic])

sets/adds the slot ‘key’ with the value ‘val’. If bstatic is true the slot will be added as static. If the slot does not exists , it will be created.

class.getfuncinfos()

If class has _call() metamethod, get info about it (see function.getfuncinfos() for details).

class.getmetamethod(name)

Returns metamethod closure (e.g. Foo.getmetamethod(“_add”)) or null if method is not implemented in class.

class.__merge(table_or_class_1, [table_or_class_2, ][table_or_class_3, ]...)

This delegate is used to create new class from old and given. Arguments to merge fields from can be tables, classes and instances.

class.__update(table_1, [table_2, ][table_3, ]...)

This delegate is used to update new table with values from given ones. In other words it mutates table with data from provided tables.

class.lock()

Seals the class protecting from modifying its fields event if it was not instantinated yet.

1.16.10. Class Instance

instance.getclass()

returns the class that created the instance.

instance.rawin(key)
Arguments
  • key – ze key

returns true if the slot ‘key’ exists. the function has the same effect as the operator ‘in’ but does not employ delegation.

instance.weakref()

returns a weak reference to the object.

instance.tostring()

tries to invoke the _tostring metamethod, if failed. returns “(instance : pointer)”.

instance.rawget(key)

tries to get a value from the slot ‘key’ without employing delegation

instance.rawset(key, val)

sets the slot ‘key’ with the value ‘val’ without employing delegation. If the slot does not exists, it will be created.

instance.getfuncinfos()

If instance has _call() metamethod, get info about it (see function.getfuncinfos() for details).

instance.getmetamethod(name)

Returns metamethod closure (e.g. foo.getmetamethod(“_add”)) or null if method is not implemented in class.

instance.is_frozen()

Return true if reference to the instance is frozen with ‘freeze’ global function.

1.16.11. Generator

generator.getstatus()

returns the status of the generator as string : “running”, “dead” or “suspended”.

generator.weakref()

returns a weak reference to the object.

generator.tostring()

returns the string “(generator : pointer)”.

1.16.12. Thread

thread.call(...)

starts the thread with the specified parameters

thread.wakeup([wakeupval])

wakes up a suspended thread, accepts a optional parameter that will be used as return value for the function that suspended the thread(usually suspend())

thread.wakeupthrow(objtothrow[, propagateerror = true])

wakes up a suspended thread, throwing an exception in the awaken thread, throwing the object ‘objtothrow’.

thread.getstatus()

returns the status of the thread (“idle”,”running”,”suspended”)

thread.weakref()

returns a weak reference to the object.

thread.tostring()

returns the string “(thread : pointer)”.

thread.getstackinfos(stacklevel)

returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on).

1.16.13. Weak Reference

weakreference.ref()

returns the object that the weak reference is pointing at; null if the object that was point at was destroyed.

weakreference.weakref()

returns a weak reference to the object.

weakreference.tostring()

returns the string “(weakref : pointer)”.

1.16.14. Userdata

userdata.getfuncinfos()

If userdata has _call() metamethod in delegate, get info about it (see function.getfuncinfos() for details).