Comments ! ~ -(negative) # Comment to end of line. * / % #-…-# Multi-line comment. + - << >> (bitwise shift operators) Identifier & (bitwise and) A string start with an underscore or letter, followed by some ^ (bitwise xor) underscore, letters or numbers (case sensitive). Identifiers are | (bitwise or) generally used as names of objects or variables. .. (connect or range) Reserved Identifiers < <= > >= if elif else while for def == != end class break continue return true && (stops on false, returns last evaluated value) false nil var do import as || (stops on true, returns last evaluated value) Operators + - ( ) [ ] . - ! ~ * / % + - << ? : (conditional expression) >> & ^ | .. < <= > >= == != && || ? = (= and other assignment operators) : = += -= *= /= %= &= |= ^= <<= >>= { } Conditional expression String condition ? expression1 : expression2 '…' "…" If the value of condition is true, then expression1 will string delimiters; special characters need to be escaped: be executed, otherwise expression2 will be executed. The \a bell \b backspace \f form feed conditional expression return the the last evaluated value. \n newline \r return \t tab \v vert. tab \\ backslash \' single quote Logical operations and Boolean \" double quote \? question \0 NULL The condition detection operation require a Boolean value, \ooo character represented octal number. and non-boolean type will do the following conversion: \xhh character represented hexadecimal number. nil Convert to false. number 0 is converted to false, others are converted to Types true. nil Means no value (written as nil). instance Try to use the result of the tobool() method, boolean Contains true and false. otherwise it will be converted to true. integer Signed integer number. other Convert to true. real Floating point number. string Can include any character (and zero). Scope, blocks and chunks function First class type, can be assigned as a value. block Is the body of a control structure, body of a function class Instance template, read only. or a chunk. The block consists of several statements. instance Object constructed by class. chunk A file or string of script. module Read-write key-value pair table. Variables defined in the chunk have a global scope, and list Variable-length ordered container class. those defined in other blocks have a local scope. map Read-write hash key-value container class. Control structures range Integer range class. if cond block {elif cond block} [else block] end Variable and Assignment examples do block end a = 1 Simple assignment (or declare variables). while cond block end var a Declare variables and initialize to nil. for id : expr block end iterative statement. var a, b Declare multiple variables. for id = expr, cond[, expr] block end loop for statement, var a=0,b=1 Declare multiple variables and initialize. (not support now). a = 1 + 3 Operation and assignment. break exits loop (must be in while or for statement). continue start the next iteration of the loop (must be in Expression and Statement while or for statement). expression Consist of operators, operands, and group- return [expr] exit function and return a (nil) value. ing symbols (brackets), etc. All expressions NOTE: expression aka. expr; identifier aka. id; and con- are evaluable. dition aka. cond. statement The most basic execution unit. Consists of an assignment expression or function call Function and Lambda expression expression. def name (args) block end Statement examples: A named function is a statement, the name is a identifier. 4.5 A simple expression, just an operand. def (args) block end !true Logical not expression, unary operation. An anonymous function is an expression. 1+2 An addition expression, binary operation. /args-> expr print(12) Function call expression. Lambda expression, the return value is expr. id {, id} classname(object) Arguments list (aka. args), Lambda expression arguments Get the class name of object. The object is a class or an list can omit “,”. instance. Class and Instance classof(object) class name [: super] Get the class of object, and return nil when it fails. {var id{, id} | def id (args) block end} number(expr) int(expr) real(expr) end Convert expr to a number (automatically detect integer or class consists of the declaration of some member variables real), integer or real respectively, and return 0 or 0.0 if the and methods. name is the class name (an identifier); super conversion fails. is the super class (an expression). str(expr) Convert expr to a string. For instance, it will try to call List Instance the tostring method. l=[] New empty list value. module([name]) l=[0] The list has a value “0”. Create an empty module, and name is an optional module l=[[],nil] l[0]==[] and l[1]==nil; different types of name. values can be stored in the list. size(expr) Map Instance Get the length of the string or instance (by calling the size m={} New empty map value. method). m=[0:'ok','k':nil] l[0]=='ok' and l['k']==nil; compile(text [, mode]) the key can be any value that is When mode is 'string', text is evaluated as a script, and not nil. when mode is 'file', a script file whose path is text is read and evaluated. The mode is 'string' by default. Range Instance issubclass(sub, sup) r=0..5 New range from 0 to 5. Returns true if sub (class) is sup (class or instance) or its Exception handling derived class, otherwise return false. throw exception [, message] isinstance(obj, base) Thorw a exception value and unnecessary message value. Returns true if obj is an instance of base (class or instance) try or its derived class, otherwise return false. block { open(path[, mode]) except ((expr {, expr} | ..) [as id [, id]] | ..) Open a file by path and return an instance of this file. block The file is opened in the specified mode: } end 'r' read-only mode, the file must exist. One or more except blocks must exist. Only runtime ex- 'w' write-only mode, always create a empty file. ceptions can be catch. 'a' Create a empty file or append to the end of an Some except statements examples: existing file. except .. Catch all exceptions, but no excep- 'r+' read-write mode, the file must exist. tion variables. 'w+' read-write mode, always create a empty file. except 0,1 as .. Capture 0 and 1, no exception vari- 'a+' read-write mode, create a empty file or append to ables. the end of an existing file. except .. as e Capture all exception to variable e. 'b' binary mode, it can be combined with other access except 0 as e Capture exception 0 to variable e. modes. except .. as e,m Capture all exception to variable e, and save the message to variable m. File Members file.write(text) Basic Library Write the text to the file. file.read([count]) Global Functions If the count is specified, the number of bytes will be read, assert(expr [, msg]) otherwise the entire file will be read. Throw 'assert_failed' when expr is false, and msg is file.readline() an optional exception message. Read a line from the file (the newline character is deter- print(…) mined by the platform). Print all arguments to stdout. input([prompt]) file.seek(offset) Read a line of text from stdin, prompt is optional prompt Set the file pointer to offset. message. file.tell() super(object) Get the offset of the file pointer. Get the super class of object. The object is a class or an file.size() instance. Get the size of the file. type(expr) file.flush() Get the type name string of expr. Flush the file buffer. file.close() map.item(key) Close the file. Get the value mapped by the key. It will throw a "key_error" exception when the key-value pair does not List Members exist. list.init(args) map.setitem(key, value) Constructor, put the elements in args into list one by one. Set the value mapped by the key. If the key-value pair list.tostring() does not exist, a new one will be inserted. Serialized the list instance. map.find(key) list.push(value) Get the value mapped by the key. It will return nil when Append the value to the tail of the list. the key-value pair does not exist. list.pop([index]) map.size() Remove the element at index (the default index is −1) Get the number of key-value pairs in the map instance. from the list. map.iter() list.insert(index, value) Get the value iterator function of the map instance. Insert the value before the element at index. list.item(index) Range Members Get the element at index. The index can be an integer, rang.init(lower, upper) and a list or range instance. The constructor. The range is from lower to upper, and list.setitemindex, value) the step is 1. Set the element referenced at index to value. rang.tostring() list.size() Serialized the rang instance. Get the number of elements in the list instance. rang.lower() list.resize(expr) Get the lower value of the range instance. Modify the number of elements to the value of expr. The rang.upper() added elements are set to nil, and the reduced elements Get the upper value of the range instance. are discarded. rang.iter() list.clear() Get the value iterator function of the range instance. Clear all elements in the list instance. list.iter() Get the iterator function of the list instance. The String Library list.concat() Import Module Serialize and concatenate all elements in the list instance import string into a string. list.reverse() Basic operations Reverse the order of all elements in the list instance. string.count(s, sub[, begin[, end]]) list.copy() Count the number of occurrences of the sub string in the Copy the list instance, not copy the element but keep the string s. Search from the position between begin and end reference. of s (default is 0 and size(s)). list() .. expr string.split(s, pos) Append the value of expr to the tail of the list instance Split the string s into two substrings at position pos, and and return that instance. returns the list of those strings. list() + list() string.split(s, sep[, num]) Concatenate two list instances and return the left operand Splits the string s into substrings wherever sep occurs, and instance. returns the list of those strings. Split at most num times list() == expr (default is string.count(s, sep)). Check if two list instances are equal. It checks all elements string.find(s, sub[, begin[, end]]) one by one. Check whether the string s contains the substring sub. If list() != expr the begin and end (default is 0 and size(s)) are specified, Check if two list instances are not equal. It checks all ele- they will be searched in this range. ments one by one. hex(number) Convert number to hexadecimal string. Map Members byte(s) map.init() Get the code value of the first byte of the string s. Constructor. char(number) map.tostring() Convert the number used as the code to a character. Serialized the map instance. map.insert(key, value) Formatting Insert a key-value pair and return true, and return false string.format(fmt[, args]) when the insertion fails (e.g. the pair already exists). Returns a formatted string. The pattern starting with '%' map.remove(key) in the formatting template fmt will be replaced by the value Remove the key-value pair by the key. of [args]: %[flags][fieldwidth][.precision]type Types %d Decimal integer. %o Octal integer. %x %X Hexadecimal integer lowercase, uppercase. %x %X Octal integer. %f Floating-point in the form [-]nnnn.nnnn. %e %E Floating-point in exp. form [-]n.nnnn e [+|- ]nnn, uppercase if %E. %g %G Floating-point as %f if −4 < exp. ≤ precision, else as %e; uppercase if %G. %c Character having the code passed as integer. %s String with no embedded zeros. %q String between double quotes, with special characters escaped. %% The '%' character (escaped). Flags - Left-justifies, default is right-justify. + Prepends sign (applies to numbers). (space) Prepends sign if negative, else space. # Adds "0x" before %x, force decimal point; for %e, %f, leaves trailing zeros for %g. Field width and precision n Puts at least n characters, pad with blanks. 0n Puts at least n characters, left-pad with zeros. .n Use at least n digits for integers, rounds to n deci- mals for floating-point or no more than n chars. for strings.