Adding vscript implementation

This commit is contained in:
James Mitchell 2020-05-15 19:17:08 +10:00
parent d840c57b4a
commit 9223601321
156 changed files with 27754 additions and 0 deletions

View File

@ -969,6 +969,11 @@ int CHLClient::Init( CreateInterfaceFn appSystemFactory, CreateInterfaceFn physi
if ( !CommandLine()->CheckParm( "-noscripting") ) if ( !CommandLine()->CheckParm( "-noscripting") )
{ {
scriptmanager = (IScriptManager *)appSystemFactory( VSCRIPT_INTERFACE_VERSION, NULL ); scriptmanager = (IScriptManager *)appSystemFactory( VSCRIPT_INTERFACE_VERSION, NULL );
if (scriptmanager == nullptr)
{
scriptmanager = (IScriptManager*)Sys_GetFactoryThis()(VSCRIPT_INTERFACE_VERSION, NULL);
}
} }
#ifdef WORKSHOP_IMPORT_ENABLED #ifdef WORKSHOP_IMPORT_ENABLED

View File

@ -11,6 +11,8 @@ $Configuration
$PreprocessorDefinitions "$BASE;ASW_PROJECTED_TEXTURES;DYNAMIC_RTT_SHADOWS" $PreprocessorDefinitions "$BASE;ASW_PROJECTED_TEXTURES;DYNAMIC_RTT_SHADOWS"
$PreprocessorDefinitions "$BASE;MAPBASE_RPC;DISCORD_RPC;STEAM_RPC" [$MAPBASE_RPC] $PreprocessorDefinitions "$BASE;MAPBASE_RPC;DISCORD_RPC;STEAM_RPC" [$MAPBASE_RPC]
$PreprocessorDefinitions "$BASE;MAPBASE_VSCRIPT" [$MAPBASE_VSCRIPT]
} }
} }
@ -51,4 +53,9 @@ $Project
} }
} }
} }
$Folder "Link Libraries"
{
$Lib "vscript" [$MAPBASE_VSCRIPT]
}
} }

View File

@ -634,6 +634,11 @@ bool CServerGameDLL::DLLInit( CreateInterfaceFn appSystemFactory,
if (!CommandLine()->CheckParm("-noscripting")) if (!CommandLine()->CheckParm("-noscripting"))
{ {
scriptmanager = (IScriptManager*)appSystemFactory(VSCRIPT_INTERFACE_VERSION, NULL); scriptmanager = (IScriptManager*)appSystemFactory(VSCRIPT_INTERFACE_VERSION, NULL);
if (scriptmanager == nullptr)
{
scriptmanager = (IScriptManager*)Sys_GetFactoryThis()(VSCRIPT_INTERFACE_VERSION, NULL);
}
} }
// If not running dedicated, grab the engine vgui interface // If not running dedicated, grab the engine vgui interface

View File

@ -9,6 +9,8 @@ $Configuration
$Compiler $Compiler
{ {
$PreprocessorDefinitions "$BASE;ASW_PROJECTED_TEXTURES;DYNAMIC_RTT_SHADOWS" $PreprocessorDefinitions "$BASE;ASW_PROJECTED_TEXTURES;DYNAMIC_RTT_SHADOWS"
$PreprocessorDefinitions "$BASE;MAPBASE_VSCRIPT" [$MAPBASE_VSCRIPT]
} }
} }
@ -81,4 +83,9 @@ $Project
} }
} }
} }
$Folder "Link Libraries"
{
$Lib "vscript" [$MAPBASE_VSCRIPT]
}
} }

View File

@ -31,6 +31,12 @@ extern ScriptClassDesc_t * GetScriptDesc( CBaseEntity * );
#endif // VMPROFILE #endif // VMPROFILE
#ifdef MAPBASE_VSCRIPT
// This is to ensure a dependency exists between the vscript library and the game DLLs
extern int vscript_token;
int vscript_token_hack = vscript_token;
#endif
HSCRIPT VScriptCompileScript( const char *pszScriptName, bool bWarnMissing ) HSCRIPT VScriptCompileScript( const char *pszScriptName, bool bWarnMissing )

View File

@ -51,6 +51,7 @@ $Group "everything"
"vice" "vice"
"vrad_dll" "vrad_dll"
"vrad_launcher" "vrad_launcher"
"vscript"
"vtf2tga" "vtf2tga"
"vtfdiff" "vtfdiff"
"vvis_dll" "vvis_dll"

View File

@ -111,6 +111,11 @@ $Project "vrad_launcher"
"utils\vrad_launcher\vrad_launcher.vpc" [$WIN32] "utils\vrad_launcher\vrad_launcher.vpc" [$WIN32]
} }
$Project "vscript"
{
"vscript\vscript.vpc"
}
$Project "vtf2tga" $Project "vtf2tga"
{ {
"utils\vtf2tga\vtf2tga.vpc" [$WIN32] "utils\vtf2tga\vtf2tga.vpc" [$WIN32]

View File

@ -21,6 +21,9 @@ $Conditional MAPBASE "1"
// Toggles Mapbase's RPC implementation // Toggles Mapbase's RPC implementation
$Conditional MAPBASE_RPC "1" $Conditional MAPBASE_RPC "1"
// Toggles VScript implementation (note: interfaces still exist, just the provided implementation is not present)
$Conditional MAPBASE_VSCRIPT "1"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
$Configuration "Debug" $Configuration "Debug"

6
sp/src/vscript/squirrel/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
# Folders created at compilation
bin/
lib/
# Folders created at documentation generation
doc/build/

View File

@ -0,0 +1,17 @@
language: cpp
compiler:
- gcc
- clang
# Travis VMs are 64-bit but we compile both for 32 and 64 bit. To enable the
# 32-bit builds to work, we need gcc-multilib.
addons:
apt:
packages:
- gcc-multilib
- g++-multilib
# Enable container-based builds.
sudo: false
script: mkdir build && cd build && cmake .. && make -j2

View File

@ -0,0 +1,109 @@
cmake_minimum_required(VERSION 3.4)
project(squirrel VERSION 3.1 LANGUAGES C CXX)
option(DISABLE_STATIC "Avoid building/installing static libraries.")
option(LONG_OUTPUT_NAMES "Use longer names for binaries and libraries: squirrel3 (not sq).")
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release")
endif ()
include(GNUInstallDirs)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}")
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}")
set(CMAKE_CXX_STANDARD 11)
if(CMAKE_COMPILER_IS_GNUCXX)
add_compile_options(
"$<$<COMPILE_LANGUAGE:CXX>:-fno-rtti;-fno-exceptions>"
-fno-strict-aliasing
-Wall
-Wextra
-pedantic
-Wcast-qual
"$<$<CONFIG:Release>:-O3>"
"$<$<CONFIG:RelWithDebInfo>:-O3;-g>"
"$<$<CONFIG:MinSizeRel>:-Os>"
"$<$<CONFIG:Debug>:-pg;-pie;-gstabs;-g3;-Og>"
)
elseif(MSVC)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif()
add_subdirectory(squirrel)
add_subdirectory(sqstdlib)
add_subdirectory(sq)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(tgts)
if(NOT DISABLE_DYNAMIC)
list(APPEND tgts squirrel sqstdlib sq)
endif()
if(NOT DISABLE_STATIC)
list(APPEND tgts squirrel_static sqstdlib_static sq_static)
endif()
foreach(t ${tgts})
target_compile_definitions(${t} PUBLIC -D_SQ64)
endforeach()
endif()
if(NOT DISABLE_DYNAMIC)
set_target_properties(squirrel sqstdlib PROPERTIES SOVERSION 0 VERSION 0.0.0)
endif()
if(NOT SQ_DISABLE_INSTALLER AND NOT SQ_DISABLE_HEADER_INSTALLER)
install(FILES
include/sqconfig.h
include/squirrel.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT Development
)
install(FILES
include/sqstdaux.h
include/sqstdblob.h
include/sqstdio.h
include/sqstdmath.h
include/sqstdstring.h
include/sqstdsystem.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT Development
)
endif()
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}/cmake/squirrel/squirrel-config-version.cmake"
VERSION "${squirrel_VERSION}"
COMPATIBILITY AnyNewerVersion
)
configure_package_config_file(
"${CMAKE_CURRENT_SOURCE_DIR}/squirrel-config.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}/cmake/squirrel/squirrel-config.cmake"
INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/squirrel"
)
export(EXPORT squirrel
NAMESPACE squirrel::
FILE "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}/cmake/squirrel/squirrel-targets.cmake"
)
if(NOT SQ_DISABLE_INSTALLER AND NOT SQ_DISABLE_CMAKE_INSTALLER)
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}/cmake/squirrel/squirrel-config-version.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}/cmake/squirrel/squirrel-config.cmake"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/squirrel"
COMPONENT Development
)
install(EXPORT squirrel
NAMESPACE squirrel::
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/squirrel"
FILE "squirrel-targets.cmake"
COMPONENT Development
)
endif()

View File

@ -0,0 +1,86 @@
Squirrel 3.1 stable
--------------------------------------------------------
What is in this distribution?
squirrel
static library implementing the compiler and interpreter of the language
sqstdlib
the standard utility libraries
sq
stand alone interpreter
doc
The manual
etc
a minimalistic embedding sample
samples
samples programs
HOW TO COMPILE
---------------------------------------------------------
CMAKE USERS
.........................................................
If you want to build the shared libraries under Windows using Visual
Studio, you will have to use CMake version 3.4 or newer. If not, an
earlier version will suffice. For a traditional out-of-source build
under Linux, type something like
$ mkdir build # Create temporary build directory
$ cd build
$ cmake .. # CMake will determine all the necessary information,
# including the platform (32- vs. 64-bit)
$ make
$ make install
$ cd ..; rm -r build
The default installation directory will be /usr/local on Unix platforms,
and C:/Program Files/squirrel on Windows. The binaries will go into bin/
and the libraries into lib/. You can change this behavior by calling CMake like
this:
$ cmake .. -DCMAKE_INSTALL_PREFIX=/some/path/on/your/system
With the CMAKE_INSTALL_BINDIR and CMAKE_INSTALL_LIBDIR options, the directories
the binaries & libraries will go in (relative to CMAKE_INSTALL_PREFIX)
can be specified. For instance,
$ cmake .. -DCMAKE_INSTALL_LIBDIR=lib64
will install the libraries into a 'lib64' subdirectory in the top
source directory. The public header files will be installed into the directory
the value of CMAKE_INSTALL_INCLUDEDIR points to. If you want only the
binaries and no headers, just set -DSQ_DISABLE_HEADER_INSTALLER=ON, and no
header files will be installed.
Under Windows, it is probably easiest to use the CMake GUI interface,
although invoking CMake from the command line as explained above
should work as well.
GCC USERS
.........................................................
There is a very simple makefile that compiles all libraries and exes
from the root of the project run 'make'
for 32 bits systems
$ make
for 64 bits systems
$ make sq64
VISUAL C++ USERS
.........................................................
Open squirrel.dsw from the root project directory and build(dho!)
DOCUMENTATION GENERATION
.........................................................
To be able to compile the documentation, make sure that you have Python
installed and the packages sphinx and sphinx_rtd_theme. Browse into doc/
and use either the Makefile for GCC-based platforms or make.bat for
Windows platforms.

View File

@ -0,0 +1,21 @@
Copyright (c) 2003-2017 Alberto Demichelis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------
END OF COPYRIGHT

View File

@ -0,0 +1,533 @@
***version 3.2 stable***
-added sq_tailcall
-added rawcall keyword
-added post call initializer syntax
-added table.keys() and table.values()
-added table.filter()
-additional parameters in array.map() and array.apply()
-additional optional initializer in array.reduce()
-closure.call() is now a "native tailcall" and the invoked function can now be suspended
-fixed sq_newmember and sq_rawnewmember properly pop parameters
-fixed capturing free variable on for loop counter before a break statement
-fixed \u in lexer
-various bugfixes
***version 3.1.1 stable***
-sq_gettypetag doesn't set last error(it's treated as SQBool function but keeps a SQRESULT for backward compatibility)
-fixed _set method in userdata delegates
-fixed some warnings
***version 3.1 stable***
-added slice range for tolower and toupper
-added startswith() and endswith() in string lib
-added SQ_EXCLUDE_DEFAULT_MEMFUNCTIONS to exclude default mem fuction from compilation
-added sq_getreleasehook
-added thread.wakeupthrow()
-added sq_pushthread
-added \u and \U escape sequence for UTF8,UTF16 or UCS4 characters
-added CMake scripts(thx Fabian Wolff)
-the escape character \x is based on sizeof(SQChar)
-fixed several warnings(thx Markus Oberhumer)
-fixed optimizer bug in compound arith oprators(+=,-= etc...)
-fixed sq_getrefvmcount() (thx Gerrit)
-fixed sq_getrefcount() when no references were added with sq_addref() (thx Gerrit)
-fixed bug in string.tointeger() (thx Domingo)
-fixed weakref comparison in 32bit builds using doubles(thx Domingo)
-fixed compiler bug(thx Peter)
-fixed some error in the documentation(thx Alexander)
-fixed some error reporting in compiler(thx Alexander)
-fixed incorrect optional semicolon after "if block"(thx Alexander)
-fixed crash bug in compiler related to compound arith operators(+=,-= etc...) (thx Jeff1)
***2015-01-10 ***
***version 3.1 RC 1***
-added new header sqconfig.h for all optional type declarations(unicode, 64bits etc..)
-added sq_setsharedforeignptr sq_getsharedforeignptr
-added sq_setsharedreleasehook sq_getsharedreleasehook
-added escape() in sqstd string library
-added __LINE__ and __FILE__ (thx mingodad)
-widechar support on gcc builds
-now boolean can be used in constants
-reduced dependencies on C runtime library
-newthread and sq_newthread() no longer reinitialize the root table on friend VMs(thx Lucas Cardellini)
-exceptions in the _inherited metamethod are propagated(thx Lucas Cardellini)
-'in' operator performance improvement(thx unagipai and mingodad)
-fixes crash in compiler when trying to write 'base'
-fixed bug in switch statement when using locals as case values (thx mingodad)
-fixed bug in print()(thx Lucas Cardellini)
***2013-08-30 ***
***version 3.1 beta 1***
-added new scoping rule(root attached to closures)
-added closure.setroot() closure.getroot()
-added sq_setclosureroot() and sq_getclosureroot()
-added sq_setvmreleasehook() and sq_getvmreleasehook()
-added documentaion for sq_getbase()
-now string.tointeger() accepts an optional parameter 'base'
-now format accepts zeroes in the format string (thx mingodad)
-fixed bug in sqstd_createfile() (thx mingodad)
-minor buxfixes
***2012-11-10 ***
***version 3.0.4 stable***
-sq_deleteslot slot now pops the key in case of failure
-fixed bug when _get metamethod throws null
-fixed a bug in rstrip
-added some error handling
-minor bugfixes
***2012-06-19 ***
***version 3.1.0 alpha 1***
-changed in and instanceof operator precendence
-root object in closures
-added closure.setroot closure.getroot
-added sq_setclosureroot and sq_getclosureroot
***version 3.0.3 stable***
-improved error messages for _cmp(when a non integer value is returned) (thx Yexo)
-added class.newmember() built in method (thx Nam)
-added class.rawnewmember() built in method (thx Nam)
-added sq_rawnewmember() (thx Nam)
-added sq_getversion()
-added sq_typeof()
-added sq_getclosurename()
-added file.close() in stdlib
-documented closure.getinfos() built-in method
-fixed string iteration doesn't return negative numbers for characters > 127
-fixed bug in tofloat() when converting a string with scientific notation without a decimal point (thx wr2)
-fixed potential infinite loop in array.sort() when the _cmp function is inconsistent (thx Yexo)
-fixed obscure bug in the compiler(thx yishin)
-fixed some minor bug
***2011-11-28 ***
***version 3.0.2 stable***
-added sq_gethash API
-now array.sort() is implemented with heapsort
-now floats in scientific notation also accept numbers with no '.' (eg. 1e+6 or 1e6)
-fixed some warning
-fixed some documentation
-fixed bug in GC
***2011-09-08 ***
***version 3.0.1 stable***
-added # as alternative symbol for "line comment"(mostly useful for shell scripts)
-added sq_throwobject() to throw an arbitrary object from the C API
-added alignement flag for userdata types, SQ_ALIGNMENT (thx Shigemasa)
-added rawset() and rawget() to class and instance default delegate
-changed bytecode format now ensures matching integer size and float size
-now inherited classes also inherit userdatasize
-added SQUIRREL_VERSION_NUMBER in squirrel.h and _versionnumber_ global symbol
-fixed sq_getmemberhandle
-fixed sq_getrefcount
-refactored some sqstdio code
-refactored some clone code
-refactored some stuff in the string lib
-added -s and -fno-exceptions in GCC makefile(better performance when using GCC)
***2011-03-13 ***
***version 3.0 stable***
-added sq_getcallee()
-sq_getfreevariable() also works for native closures
-minior optimizations
-removed several warning when compiling with GCC 4.x
-fixed some errors in the documentation
-fixed bug when using SQUSEDOUBLE and 32bits intengers
-fixed bug when invoking generators with closure.call() (thx huntercool)
***2010-12-19 ***
***version 3.0 release candidate 1(RC 1)***
-improved metamethods error handling
-added parameter 'isstatic' to _newmember metamethod(thx G.Meyer)
-added sq_getrefcount() to return number of refences from C++(thx G.Meyer)
***2010-11-07 ***
***version 3.0 beta 3***
-license changed to "MIT license"
-added sq_resurrectunreachable() and resurrectunreachable()
-added callee() built in function, returns the current running closure
-added thread.getstackinfos()
-added sq_objtouserpointer()
-added sq_newtableex()
-various refactoring and optimizations
-fixed several 64bits issues regarding integer to string conversions
-fixed some bugs when SQUSEDOUBLE is used in 32bits systems
***2010-08-18 ***
***version 3.0 beta 2.1***
-fixed bug in class constructor
-fixed bug in compound arith
***2010-08-12 ***
***version 3.0 beta 2***
-class methods can be added or replaced after the class as been instantiated
-JSON compliant table syntax, this is currently an experimental feature (thx atai)
-sq_getsize() now returns userdatasize for classes and instances
-now setroottable() and setconsttable() return the previous value of the respective table
-fixed bug in compound arith operators when used on a free variable (thx ellon)
-fixed some x64 minor bugs
-fixed minor bug in the compiler
-refactored some VM internals
-documented sq_getmemberhandle, sq_getbyhandle, sq_setbyhandle to set and get value from classes
***2009-11-15 ***
***version 3.0 beta 1***
-various refactoring and optimizations
-fixed bug in free variables (thx mokehehe)
-fixed bug in functions with default parameters (thx ara & Yexo)
-fixed bug in exception handling
-improved error propagation in _set and _get metamethods ( and 'throw null' for clean failure)
-added sq_getmemberhandle, sq_getbyhandle, sq_setbyhandle to set and get value from classes
***2009-06-30 ***
***version 3.0 alpha 2***
-added real free variables(thx Paul Ruizendaal)
-added refactored function call implementation and compiler(thx Paul Ruizendaal)
-added sq_getfunctioninfo
-added compile time flag SQUSEDOUBLE to use double precision floats
-added global slot _floatsize_ int the base lib to recognize single precision and double precision builds
-sq_wakeupvm can now resume the vm with an exception
-added sqstd_format
-now blobs can be cloned
-generators can now be instantiated by calling sq_call() or closure.call()
-fixed debughook bug
-fixed cooroutine error propagation
***2008-07-23 ***
***version 3.0 alpha 1***
-first branch from 2.x source tree
-added 'base' keyword
-removed 'delegate' keyword
-now compiled scripts are vararg functions
-added setdelegate() and getdelegate() table builtin methods
-added <=> 3 ways compare operator
-added lambda expression @(a,b) a + b
-added local function statement
-added array built-in map(),reduce(),apply(),filter() and find()
-generators hold only a weak reference of the enviroment object
-removed 'vargv' and 'vargc' keywords
-now var args are passed as an array called vargv(as a paramter)
-removed 'parent' keyword
-added class getbase() built in method
-instanceof doesn't throw an exception if the left expression is not a class
-lexical scoping for free variables(free variables are no longer in the second parameter list)
-sq_setprintfunc accept error func
-sq_geterrorfunc()
-added sq_arrayremove() and sq_arrayinsert()
-error() built in function(works like print but prints using the errorfunc)
-added native debug hook
***2008-02-17 ***
***version 2.2 stable***
-added _newslot metamethod in classes
-added enums added constants
-added sq_pushconsttable, sq_setconsttable
-added default param
-added octal literals(thx Dinosaur)
-fixed debug hook, 'calls' and 'returns' are properly notified in the same number.
-fixed a coroutine bug
***2007-07-29 ***
***version 2.1.2 stable***
-new behaviour for generators iteration using foreach
now when a generator is iterated by foreach the value returned by a 'return val' statement
will terminate the iteration but will not be returned as foreach iteration
-added sq_setclassudsize()
-added sq_clear()
-added table.clear(), array.clear()
-fixed sq_cmp() (thx jyuill)
-fixed minor bugs
***2006-08-21 ***
***version 2.1.1 stable***
-vm refactoring
-optimized internal function memory layout
-new global symbol _version_ (is the version string)
-code size optimization for float literals(on 32bits float builts)
-now the raw ref API(sq_addref etc...) is fully reentrant.
-fixed a bug in sq_getdelegate() now pushes null if the object doesn't have a delegate(thx MatzeB)
-improved C reference performances in NO_GARBAGE_COLLECTOR builds
-sq_getlocal() now enumerates also outer values.
-fixed regexp library for GCC users.
***2006-03-19 ***
***version 2.1 stable***
-added static class fields, new keyword static
-added 64bits architecture support
-added global slot _intsize_ int the base lib to recognize 32bits and 64bits builds
-added functions with fixed environment, closure.bindenv() built-in function
-all types except userdata and null implement the tostring() method
-string concatenation now invokes metamethod _tostring
-new metamethods for class objects _newmember and _inherited
-sq_call() sq_resume() sq_wakeupvm() have a new signature
-new C referencing implementation(scales more with the amount of references)
-refactored hash table
-new api functions sq_newslot(),sq_tobool(),sq_getbase(), sq_instanceof(), sq_bindenv()
-the api func sq_createslot was deprecated but still supported in form of C macro on top of sq_newslot
-sq_setreleasehook() now also works for classes
-stream.readstr() and stream.writestr() have been deprecated(this affects file and blob)
-fixed squirrel.h undeclared api calls
-fixed few minor bugs
-SQChar is now defined as wchar_t
-removed warning when building with -Wall -pedantic for GCC users
-added new std io function writeclosuretofile()
-added new std string functions strip(),rstrip(),lstrip() and split()
-regular expressions operators (+,*) now have more POSIX greedyness behaviour
-class constructors are now invoked as normal functions
***2005-10-02 ***
***version 2.0.5 stable***
-fixed some 64bits incompatibilities (thx sarge)
-fixed minor bug in the stdlib format() function (thx Rick)
-fixed a bug in dofile() that was preventing to compile empty files
-added new API sq_poptop() & sq_getfreevariable()
-some performance improvements
***2005-08-14 ***
***version 2.0.4 stable***
-weak references and related API calls
-added sq_objtobool()
-class instances memory policies improved(1 mem allocation for the whole instance)
-typetags are now declared as SQUserPointer instead of unsigned int
-first pass for 64bits compatibility
-fixed minor bug in the stdio stream
-fixed a bug in format()
-fixed bug in string.tointeger() and string.tofloat()
***2005-06-24 ***
***version 2.0.3 stable***
-dofile() and loadfile() in the iolib now can decode ASCII, UTF8 files UCS2 big-endian and little-endian
-sq_setparamscheck() : now typemesk can check for null
-added string escape sequence \xhhhh
-fixed some C++ standard incompatibilities
***2005-05-15 ***
***version 2.0.2 stable***
-performances improvements (expecially for GCC users)
-removed all dependencies from C++ exception handling
-various bugfixes
***2005-04-12 ***
***version 2.0.1 stable***
-various bugfixes
-sq_setparamscheck() now allows spaces in the typemask
***2005-04-03 ***
***version 2.0 stable***
-added API sq_gettypetag()
-added built-in function to the bool type(tointeger, tostring etc...)
***2005-02-27 ***
***version 2.0 release candidate 1(RC 1)***
-added API sq_reseterror()
-modified sq_release()
-now class instances can be cloned
-various bufixes
***2005-01-26 ***
***version 2.0 beta 1***
-added bool type
-class properties can be redefined in a derived class
-added ops *= /= and %=
-new syntax for class attributes declaration </ and /> instead of ( and )
-increased the max number of literals per function from 65535 to 16777215
-now free variables have proper lexical scoping
-added API sq_createinstance(), sq_pushbool(), sq_getbool()
-added built-in function type()
-added built-in function obj.rawin(key) in table,class and instance
-sq_rawget() and sq_rawset() now work also on classes and instances
-the VM no longer uses C++ exception handling (more suitable for embedded devices)
-various bufixes
***2004-12-21 ***
***version 2.0 alpha 2***
-globals scoping changed, now if :: is omitted the VM automatically falls back on the root table
-various bufixes
-added class level attributes
***2004-12-12 ***
***version 2.0 alpha 1***
-codebase branch from version 1.x
-added classes
-added functions with variable number of parameters(vargc & vargv and the ...)
-0 and 0.0 are now considered 'false' by all conditional statements(if,while,for,?,do-while)
-added new api functions sq_newclass() sq_setinstanceup() sq_getinstanceup() sq_getattributes() sq_setattributes()
-modified api sq_settypetag()
***2004-11-01 ***
***version 1.0 stable***
-fixed some minor bug
-improved operator 'delete' performances
-added scientific notation for float numbers( eg. 2.e16 or 2.e-2)
***2004-08-30 ***
***version 1.0 release candidate 2(RC 2)***
-fixed bug in the vm(thx Pierre Renaux)
-fixed bug in the optimizer(thx Pierre Renaux)
-fixed some bug in the documentation(thx JD)
-added new api functions for raw object handling
-removed nested multiline comments
-reduced memory footprint in C references
***2004-08-23 ***
***version 1.0 release candidate 1(RC 1)***
-fixed division by zero
-the 'in' operator and obj.rawget() do not query the default delegate anymore
-added function sq_getprintfunc()
-added new standard library 'auxlib'(implements default error handlers)
***2004-07-12 ***
***version 1.0 beta 4***
-fixed a bug in the integer.tochar() built-in method
-fixed unary minus operator
-fixed bug in dofile()
-fixed inconsistency between != and == operators(on float/integer comparison)
-added javascript style unsigned right shift operator '>>>'
-added array(size) constructor built-in function
-array.resize(size,[fill]) built-in function accepts an optional 'fill' value
-improved debug API, added sq_getclosureinfo() and sq_setnativeclosurename()
***2004-05-23 ***
***version 1.0 beta 3***
-minor vm bug fixes
-string allocation is now faster
-tables and array memory usage is now less conservative(they shrink)
-added regular expression routines in the standard library
-The 'c' expression now accepts only 1 character(thx irbrian)
-multiline strings <[ ]> have been substituted with C# style verbatim strings (eg. @"string")
-added new keyword 'parent' for accessing the delegate of tables and unserdata
-The metamethod '_clone' has been renamed '_cloned'
-the _delslot metamethod's behaviour and prototype have been changed
-new default function in the integer and float object 'tochar()'
-the built-in function chcode2string has been removed
-the default method [table].getdelegate() has been removed
-new api sq_rawdeleteslot()
-new table built-in method rawdelete(key)
-the dynamic mudule loading has been removed from the standard distribution
-some optimizations in the VM
***2004-04-21 ***
***version 1.0 beta 2***
-minor compiler/parser bug fixes
-sq_newclosure has a different prototype, the "paramscheck" of paramter has been moved to the new function sq_setparamscheck()
-sq_setparamscheck allows to add automatic parameters type checking in native closures
-sq_compile() lost the lineinfo parameter
-new api sq_enabledebuginfo() globally sets compiler's debug info generation
-added consistency check on bytecode serialization
-fixed += operator, now works on strings like +
-added global slot in the base lib _charsize_ to recognize unicode builds from ascii builds runtime
-added registry table
-new api call sq_pushregistrytable()
-added type tag to the userdata type sq_settypetag()
-sq_getuserdata now queries the userdata typetag
-the built in function collect_garbage() as been renamed collectgarbage() for consistency reasons
-new standard libraries(sqlibs are now obsolete)
***2004-02-20 ***
***version 1.0 beta 1***
-fixed a bug in the compiler (thanks Martin Kofler)
-fixed bug in the switch case statement
-fixed the _unm metamethod
-fixed minor bugs in the API
-fixed automatic stack resizing
-first beta version
first pass code clean up in the VM and base lib
first pass code coverege test has been done on VM and built-in lib
-new VM creation API sq_open() sq_close() (sq_newvm and sq_releasevm are now obsolete)
-new api allows to specifiy a "print" function to output text(sq_printfunc)
-added some small optimizations
-new cooperative multi-threading capabilities in the base library(coroutines), VMs are now a built in type("thread")
-new built in functions have been added for manipulating the new "thread" type
-friend virtual machines share the same root table, error handler and debug hook by default
-new compile time options
***2004-01-19 ***
***version 0.9 alpha***
-fixed a garbage collection bug
-fixed some API bugs(thanks to Joshua Jensen)
-fixed tail calls (in the version 0.8 the tail call optimization was erroneously disabled)
-new function parameters semantic, now passing a wrong number of parameters generates an exception
-native closures have now a built in parameter number checking
-sq_rawget and sq_rawset now work also on arrays
-sq_getsize now woks also on userdata
-the userdata release hook prototype is changed(now passes the size of the userdata)
-the lexer reader function now returns an integer instead of a char that allows better error checking on the input(thx Joshua Jensen)
-faster compiler
-try/catch blocks do not cause any runtime memory allocation anymore
***2003-12-06 ***
***version 0.8 alpha***
-fixed a bug that was preventing to have callable userdata throught the metamethod _call
-fixed a garbage collection bug
-fixed == operator now can compare correctly different types
-new built in method getstackinfos(level)
-improved line informations precision for the debug hook
-new api call sq_compilebuffer()
-new built-in api function compilestring()
-new syntactic sugar for function declarations inside tables
-the debug API has been finalized
***2003-11-17 ***
***version 0.7 alpha***
-fixed critical bug SQInteger the tail call system
-fixed bug in the continue statement code generation
-fixed func call param issue(thanks to Rewoonenco Andrew)
-added _delslot metamethod(thanks to Rewoonenco Andrew)
-new multiline string expression ( delimited by <[ and ]> )
-normal strings ("") do not allow embedded new line anymore
-reduced vm memory footprint(C refs are shared between friend VMs)
-new api method sq_deleteslot()
-new debug hook event 'r' is triggered when a function returns
***2003-11-04 ***
***version 0.6 alpha***
-fixed switch statement(was executing the default case after a break)
-sq_call() doesn't pop the closure (just the params)
-the vm execution can be suspended from the C API anytime (micro-threads)
-new api calls sq_suspendvm() sq_wakeupvm() sq_getvmstate() and sq_reservestack()
***2003-10-13 ***
***version 0.5 alpha***
-fixed some minor bug
-tested with non ASCII identifiers in unicode mode(I've tried chinese chars)
-added built-in function string.find()
-the built-in function array.sort() optionally accepts a cmp(a,b) function
-the debug hook function now has a new prototype debug_hook(event_type,sourcefile,line,functionname)
-fixed some debug info imprecision
***2003-10-01 ***
***version 0.4 alpha***
-faster VM
-sq_call will pop arguments and closure also in case of failure
-fixed a bug in sq_remove
-now the VM detects delegation cycles(and throws an exception)
-new operators ++ and --
-new operator ',' comma operator
-fixed some expression precedence issue
-fixed bug in sq_arraypop
***2003-09-15 ***
***version 0.3 alpha***
-fixed a bug in array::insert()
-optional Unicode core(define SQUNICODE or _UNICODE on Win32)
-sq_compiler uses a new reader function SQLEXREADFUNC
-the debug hook passes 'l' instead of 'line' for line callbacks
and 'c' instead of 'call' for call callbacks
-new array.extend() bulit-in function
-new API sq_clone()
***2003-09-10 ***
***version 0.2 pre-alpha***
-new completely reentrant VM (sq_open and sq_close are now obsolete)
-sq_newvm() has a new prototype
-allocators are now global and linked in the VM
-_newslot meta method added
-rawset creates a slot if doesn't exists
-the compiler error callback pass the vm handle(thanks Pierre Renaux)
-sq_setforeignptr() sq_getforeingptr() are now public
-sq_resume() now is possible to resume generators from C
-sq_getlasterror() retrieve the last thrown error
-improved docs
***2003-09-06 ***
***version 0.1 pre-alpha***
first release

View File

@ -0,0 +1,22 @@
SQUIRREL=.
MAKE=make
sq32: folders
cd squirrel; $(MAKE)
cd sqstdlib; $(MAKE)
cd sq; $(MAKE)
sqprof: folders
cd squirrel; $(MAKE) sqprof
cd sqstdlib; $(MAKE) sqprof
cd sq; $(MAKE) sqprof
sq64: folders
cd squirrel; $(MAKE) sq64
cd sqstdlib; $(MAKE) sq64
cd sq; $(MAKE) sq64
folders:
mkdir -p lib
mkdir -p bin

View File

@ -0,0 +1,33 @@
The programming language SQUIRREL 3.1 stable
--------------------------------------------------
This project has successfully been compiled and run on
* Windows (x86 and amd64)
* Linux (x86, amd64 and ARM)
* Illumos (x86 and amd64)
* FreeBSD (x86 and ARM)
The following compilers have been confirmed to be working:
MS Visual C++ 6.0 (all on x86 and amd64)
7.0 |
7.1 v
8.0
9.0
10.0
12.0 ---
MinGW gcc 3.2 (mingw special 20020817-1)
Cygnus gcc 3.2
Linux gcc 3.2.3
4.0.0 (x86 and amd64)
5.3.1 (amd64)
Illumos gcc 4.0.0 (x86 and amd64)
ARM Linux gcc 4.6.3 (Raspberry Pi Model B)
Feedback and suggestions are appreciated
project page - http://www.squirrel-lang.org
community forums - http://forum.squirrel-lang.org
wiki - http://wiki.squirrel-lang.org
author - alberto@demichelis.net
END OF README

View File

@ -0,0 +1,28 @@
version: 0.0.{build}
platform:
- x86
- x64
configuration:
- Debug
- Release
clone_folder: c:\sq
before_build:
- mkdir build
- cd build
- call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" %platform%
- echo %platform%
- if %platform%==X64 (cmake .. -G "Visual Studio 14 2015 Win64")
- if %platform%==x86 (cmake .. -G "Visual Studio 14 2015")
build_script:
- cmake --build . --config %configuration% -- /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll"
artifacts:
- path: build\*\%configuration%\*.exe
- path: build\*\%configuration%\*.dll
test: off

View File

@ -0,0 +1,216 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/testy_sphinxy.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/testy_sphinxy.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/testy_sphinxy"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/testy_sphinxy"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

View File

@ -0,0 +1,263 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
REM Check if sphinx-build is available and fallback to Python version if any
%SPHINXBUILD% 1>NUL 2>NUL
if errorlevel 9009 goto sphinx_python
goto sphinx_ok
:sphinx_python
set SPHINXBUILD=python -m sphinx.__init__
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
:sphinx_ok
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\testy_sphinxy.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\testy_sphinxy.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "coverage" (
%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
if errorlevel 1 exit /b 1
echo.
echo.Testing of coverage in the sources finished, look at the ^
results in %BUILDDIR%/coverage/python.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end

Binary file not shown.

After

Width:  |  Height:  |  Size: 318 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 393 B

View File

@ -0,0 +1,288 @@
# -*- coding: utf-8 -*-
#
# Squirrel documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 31 00:26:52 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import time
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Squirrel documentation'
copyright = '2003-%s, Alberto Demichelis' % time.strftime('%Y')
author = u'Alberto Demichelis'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'3.1'
# The full version, including alpha/beta/rc tags.
release = u'3.1 stable'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'simple_nut.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'nut.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'squirrel_doc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
_stdauthor = r'Alberto Demichelis'
latex_documents = [
('reference/index', 'reference.tex',
'Squirrel Reference Manual', _stdauthor, 'manual'),
('stdlib/index', 'stdlib.tex',
'Squirrel Standard Library', _stdauthor, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'Squirrel', u'Squirrel Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Squirrel', u'Squirrel Documentation',
author, 'Squirrel', 'The Programming Language.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

View File

@ -0,0 +1,24 @@
.. Squirrel documentation master file, created by
sphinx-quickstart on Sun Jan 31 00:26:52 2016.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Squirrel's documentation
=========================================
Contents:
.. toctree::
:maxdepth: 1
reference/index.rst
stdlib/index.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`search`

View File

@ -0,0 +1,32 @@
.. _api_ref_bytecode_serialization:
======================
Bytecode serialization
======================
.. _sq_readclosure:
.. c:function:: SQRESULT sq_readclosure(HSQUIRRELVM v, SQREADFUNC readf, SQUserPointer up)
:param HSQUIRRELVM v: the target VM
:param SQREADFUNC readf: pointer to a read function that will be invoked by the vm during the serialization.
:param SQUserPointer up: pointer that will be passed to each call to the read function
:returns: a SQRESULT
serialize (read) a closure and pushes it on top of the stack, the source is user defined through a read callback.
.. _sq_writeclosure:
.. c:function:: SQRESULT sq_writeclosure(HSQUIRRELVM v, SQWRITEFUNC writef, SQUserPointer up)
:param HSQUIRRELVM v: the target VM
:param SQWRITEFUNC writef: pointer to a write function that will be invoked by the vm during the serialization.
:param SQUserPointer up: pointer that will be passed to each call to the write function
:returns: a SQRESULT
:remarks: closures with free variables cannot be serialized
serializes(writes) the closure on top of the stack, the destination is user defined through a write callback.

View File

@ -0,0 +1,130 @@
.. _api_ref_calls:
=====
Calls
=====
.. _sq_call:
.. c:function:: SQRESULT sq_call(HSQUIRRELVM v, SQInteger params, SQBool retval, SQBool raiseerror)
:param HSQUIRRELVM v: the target VM
:param SQInteger params: number of parameters of the function
:param SQBool retval: if true the function will push the return value in the stack
:param SQBool raiseerror: if true, if a runtime error occurs during the execution of the call, the vm will invoke the error handler.
:returns: a SQRESULT
calls a closure or a native closure. The function pops all the parameters and leave the closure in the stack; if retval is true the return value of the closure is pushed. If the execution of the function is suspended through sq_suspendvm(), the closure and the arguments will not be automatically popped from the stack.
When using to create an instance, push a dummy parameter to be filled with the newly-created instance for the constructor's 'this' parameter.
.. _sq_getcallee:
.. c:function:: SQRESULT sq_getcallee(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: a SQRESULT
push in the stack the currently running closure.
.. _sq_getlasterror:
.. c:function:: SQRESULT sq_getlasterror(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: a SQRESULT
:remarks: the pushed error descriptor can be any valid squirrel type.
pushes the last error in the stack.
.. _sq_getlocal:
.. c:function:: const SQChar * sq_getlocal(HSQUIRRELVM v, SQUnsignedInteger level, SQUnsignedInteger nseq)
:param HSQUIRRELVM v: the target VM
:param SQUnsignedInteger level: the function index in the calls stack, 0 is the current function
:param SQUnsignedInteger nseq: the index of the local variable in the stack frame (0 is 'this')
:returns: the name of the local variable if a variable exists at the given level/seq otherwise NULL.
Returns the name of a local variable given stackframe and sequence in the stack and pushes is current value. Free variables are treated as local variables, by sq_getlocal(), and will be returned as they would be at the base of the stack, just before the real local variables.
.. _sq_reseterror:
.. c:function:: void sq_reseterror(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
reset the last error in the virtual machine to null
.. _sq_resume:
.. c:function:: SQRESULT sq_resume(HSQUIRRELVM v, SQBool retval, SQBool raiseerror)
:param HSQUIRRELVM v: the target VM
:param SQBool retval: if true the function will push the return value in the stack
:param SQBool raiseerror: if true, if a runtime error occurs during the execution of the call, the vm will invoke the error handler.
:returns: a SQRESULT
:remarks: if retval != 0 the return value of the generator is pushed.
resumes the generator at the top position of the stack.
.. _sq_tailcall:
.. c:function:: SQRESULT sq_tailcall(HSQUIRRELVM v, SQInteger nparams)
:param HSQUIRRELVM v: the target VM
:param SQInteger params: number of parameters of the function
Calls a closure and removes the caller function from the call stack.
This function must be invoke from a native closure and
he return value of sq_tailcall must be returned by the caller function(see example).
*.eg*
::
SQInteger tailcall_something_example(HSQUIRRELVM v)
{
//push closure and parameters here
...
return sq_tailcall(v,2);
}
.. _sq_throwerror:
.. c:function:: SQRESULT sq_throwerror(HSQUIRRELVM v, const SQChar * err)
:param HSQUIRRELVM v: the target VM
:param const SQChar * err: the description of the error that has to be thrown
:returns: the value that has to be returned by a native closure in order to throw an exception in the virtual machine.
sets the last error in the virtual machine and returns the value that has to be returned by a native closure in order to trigger an exception in the virtual machine.
.. _sq_throwobject:
.. c:function:: SQRESULT sq_throwobject(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: the value that has to be returned by a native closure in order to throw an exception in the virtual machine.
pops a value from the stack sets it as the last error in the virtual machine. Returns the value that has to be returned by a native closure in order to trigger an exception in the virtual machine (aka SQ_ERROR).

View File

@ -0,0 +1,79 @@
.. _api_ref_compiler:
========
Compiler
========
.. _sq_compile:
.. c:function:: SQRESULT sq_compile(HSQUIRRELVM v, HSQLEXREADFUNC read, SQUserPointer p, const SQChar * sourcename, SQBool raiseerror)
:param HSQUIRRELVM v: the target VM
:param HSQLEXREADFUNC read: a pointer to a read function that will feed the compiler with the program.
:param SQUserPointer p: a user defined pointer that will be passed by the compiler to the read function at each invocation.
:param const SQChar * sourcename: the symbolic name of the program (used only for more meaningful runtime errors)
:param SQBool raiseerror: if this value is true the compiler error handler will be called in case of an error
:returns: a SQRESULT. If the sq_compile fails nothing is pushed in the stack.
:remarks: in case of an error the function will call the function set by sq_setcompilererrorhandler().
compiles a squirrel program; if it succeeds, push the compiled script as function in the stack.
.. _sq_compilebuffer:
.. c:function:: SQRESULT sq_compilebuffer(HSQUIRRELVM v, const SQChar* s, SQInteger size, const SQChar * sourcename, SQBool raiseerror)
:param HSQUIRRELVM v: the target VM
:param const SQChar* s: a pointer to the buffer that has to be compiled.
:param SQInteger size: size in characters of the buffer passed in the parameter 's'.
:param const SQChar * sourcename: the symbolic name of the program (used only for more meaningful runtime errors)
:param SQBool raiseerror: if this value true the compiler error handler will be called in case of an error
:returns: a SQRESULT. If the sq_compilebuffer fails nothing is pushed in the stack.
:remarks: in case of an error the function will call the function set by sq_setcompilererrorhandler().
compiles a squirrel program from a memory buffer; if it succeeds, push the compiled script as function in the stack.
.. _sq_enabledebuginfo:
.. c:function:: void sq_enabledebuginfo(HSQUIRRELVM v, SQBool enable)
:param HSQUIRRELVM v: the target VM
:param SQBool enable: if true enables the debug info generation, if == 0 disables it.
:remarks: The function affects all threads as well.
enable/disable the debug line information generation at compile time.
.. _sq_notifyallexceptions:
.. c:function:: void sq_notifyallexceptions(HSQUIRRELVM v, SQBool enable)
:param HSQUIRRELVM v: the target VM
:param SQBool enable: if true enables the error callback notification of handled exceptions.
:remarks: By default the VM will invoke the error callback only if an exception is not handled (no try/catch traps are present in the call stack). If notifyallexceptions is enabled, the VM will call the error callback for any exception even if between try/catch blocks. This feature is useful for implementing debuggers.
enable/disable the error callback notification of handled exceptions.
.. _sq_setcompilererrorhandler:
.. c:function:: void sq_setcompilererrorhandler(HSQUIRRELVM v, SQCOMPILERERROR f)
:param HSQUIRRELVM v: the target VM
:param SQCOMPILERERROR f: A pointer to the error handler function
:remarks: if the parameter f is NULL no function will be called when a compiler error occurs. The compiler error handler is shared between friend VMs.
sets the compiler error handler function

View File

@ -0,0 +1,72 @@
.. _api_ref_debug_interface:
===============
Debug interface
===============
.. _sq_getfunctioninfo:
.. c:function:: SQRESULT sq_getfunctioninfo(HSQUIRRELVM v, SQInteger level, SQFunctionInfo * fi)
:param HSQUIRRELVM v: the target VM
:param SQInteger level: calls stack level
:param SQFunctionInfo * fi: pointer to the SQFunctionInfo structure that will store the closure informations
:returns: a SQRESULT.
:remarks: the member 'funcid' of the returned SQFunctionInfo structure is a unique identifier of the function; this can be useful to identify a specific piece of squirrel code in an application like for instance a profiler. this method will fail if the closure in the stack is a native C closure.
*.eg*
::
typedef struct tagSQFunctionInfo {
SQUserPointer funcid; //unique idetifier for a function (all it's closures will share the same funcid)
const SQChar *name; //function name
const SQChar *source; //function source file name
}SQFunctionInfo;
.. _sq_setdebughook:
.. c:function:: void sq_setdebughook(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:remarks: In order to receive a 'per line' callback, is necessary to compile the scripts with the line informations. Without line informations activated, only the 'call/return' callbacks will be invoked.
pops a closure from the stack an sets it as debug hook. When a debug hook is set it overrides any previously set native or non native hooks. if the hook is null the debug hook will be disabled.
.. _sq_setnativedebughook:
.. c:function:: void sq_setnativedebughook(HSQUIRRELVM v, SQDEBUGHOOK hook)
:param HSQUIRRELVM v: the target VM
:param SQDEBUGHOOK hook: the native hook function
:remarks: In order to receive a 'per line' callback, is necessary to compile the scripts with the line informations. Without line informations activated, only the 'call/return' callbacks will be invoked.
sets the native debug hook. When a native hook is set it overrides any previously set native or non native hooks. if the hook is NULL the debug hook will be disabled.
.. _sq_stackinfos:
.. c:function:: SQRESULT sq_stackinfos(HSQUIRRELVM v, SQInteger level, SQStackInfos * si)
:param HSQUIRRELVM v: the target VM
:param SQInteger level: calls stack level
:param SQStackInfos * si: pointer to the SQStackInfos structure that will store the stack informations
:returns: a SQRESULT.
retrieve the calls stack informations of a ceratain level in the calls stack.

View File

@ -0,0 +1,27 @@
.. _api_ref_garbage_collector:
=================
Garbage Collector
=================
.. _sq_collectgarbage:
.. c:function:: SQInteger sq_collectgarbage(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:remarks: this api only works with garbage collector builds (NO_GARBAGE_COLLECTOR is not defined)
runs the garbage collector and returns the number of reference cycles found (and deleted)
.. _sq_resurrectunreachable:
.. c:function:: SQRESULT sq_resurrectunreachable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:remarks: this api only works with garbage collector builds (NO_GARBAGE_COLLECTOR is not defined)
runs the garbage collector and pushes an array in the stack containing all unreachable object found. If no unreachable object is found, null is pushed instead. This function is meant to help debug reference cycles.

View File

@ -0,0 +1,695 @@
.. _api_ref_object_creation_and_handling:
============================
Object creation and handling
============================
.. _sq_bindenv:
.. c:function:: SQRESULT sq_bindenv(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target closure
:returns: a SQRESULT
:remarks: the cloned closure holds the environment object as weak reference
pops an object from the stack (must be a table, instance, or class); clones the closure at position idx in the stack and sets the popped object as environment of the cloned closure. Then pushes the new cloned closure on top of the stack.
.. _sq_createinstance:
.. c:function:: SQRESULT sq_createinstance(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target class
:returns: a SQRESULT
:remarks: the function doesn't invoke the instance contructor. To create an instance and automatically invoke its contructor, sq_call must be used instead.
creates an instance of the class at 'idx' position in the stack. The new class instance is pushed on top of the stack.
.. _sq_getbool:
.. c:function:: SQRESULT sq_getbool(HSQUIRRELVM v, SQInteger idx, SQBool * b)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQBool * b: A pointer to the bool that will store the value
:returns: a SQRESULT
gets the value of the bool at the idx position in the stack.
.. _sq_getbyhandle:
.. c:function:: SQRESULT sq_getbyhandle(HSQUIRRELVM v, SQInteger idx, HSQMEMBERHANDLE* handle)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack pointing to the class or instance
:param HSQMEMBERHANDLE* handle: a pointer to the member handle
:returns: a SQRESULT
pushes the value of a class or instance member using a member handle (see sq_getmemberhandle)
.. _sq_getclosureinfo:
.. c:function:: SQRESULT sq_getclosureinfo(HSQUIRRELVM v, SQInteger idx, SQInteger * nparams, SQInteger * nfreevars)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target closure
:param SQInteger * nparams: a pointer to an integer that will store the number of parameters
:param SQInteger * nfreevars: a pointer to an integer that will store the number of free variables
:returns: an SQRESULT
retrieves number of parameters and number of freevariables from a squirrel closure.
.. _sq_getclosurename:
.. c:function:: SQRESULT sq_getclosurename(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target closure
:returns: an SQRESULT
pushes the name of the closure at position idx in the stack. Note that the name can be a string or null if the closure is anonymous or a native closure with no name assigned to it.
.. _sq_getclosureroot:
.. c:function:: SQRESULT sq_getclosureroot(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target closure
:returns: an SQRESULT
pushes the root table of the closure at position idx in the stack
.. _sq_getfloat:
.. c:function:: SQRESULT sq_getfloat(HSQUIRRELVM v, SQInteger idx, SQFloat * f)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQFloat * f: A pointer to the float that will store the value
:returns: a SQRESULT
gets the value of the float at the idx position in the stack.
.. _sq_gethash:
.. c:function:: SQHash sq_gethash(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:returns: the hash key of the value at the position idx in the stack
:remarks: the hash value function is the same used by the VM.
returns the hash key of a value at the idx position in the stack.
.. _sq_getinstanceup:
.. c:function:: SQRESULT sq_getinstanceup(HSQUIRRELVM v, SQInteger idx, SQUserPointer * up, SQUSerPointer typetag)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQUserPointer * up: a pointer to the userpointer that will store the result
:param SQUSerPointer typetag: the typetag that has to be checked, if this value is set to 0 the typetag is ignored.
:returns: a SQRESULT
gets the userpointer of the class instance at position idx in the stack. if the parameter 'typetag' is different than 0, the function checks that the class or a base class of the instance is tagged with the specified tag; if not the function fails. If 'typetag' is 0 the function will ignore the tag check.
.. _sq_getinteger:
.. c:function:: SQRESULT sq_getinteger(HSQUIRRELVM v, SQInteger idx, SQInteger * i)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQInteger * i: A pointer to the integer that will store the value
:returns: a SQRESULT
gets the value of the integer at the idx position in the stack.
.. _sq_getmemberhandle:
.. c:function:: SQRESULT sq_getmemberhandle(HSQUIRRELVM v, SQInteger idx, HSQMEMBERHANDLE* handle)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack pointing to the class
:param HSQMEMBERHANDLE* handle: a pointer to the variable that will store the handle
:returns: a SQRESULT
:remarks: This method works only with classes. A handle retrieved through a class can be later used to set or get values from one of the class instances. Handles retrieved from base classes are still valid in derived classes and respect inheritance rules.
pops a value from the stack and uses it as index to fetch the handle of a class member. The handle can be later used to set or get the member value using sq_getbyhandle(), sq_setbyhandle().
.. _sq_getreleasehook:
.. c:function:: SQRELEASEHOOK sq_getreleasehook(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:remarks: if the object that position idx is not an userdata, class instance or class the function returns NULL.
gets the release hook of the userdata, class instance or class at position idx in the stack.
.. _sq_getscratchpad:
.. c:function:: SQChar * sq_getscratchpad(HSQUIRRELVM v, SQInteger minsize)
:param HSQUIRRELVM v: the target VM
:param SQInteger minsize: the requested size for the scratchpad buffer
:remarks: the buffer is valid until the next call to sq_getscratchpad
returns a pointer to a memory buffer that is at least as big as minsize.
.. _sq_getsize:
.. c:function:: SQObjectType sq_getsize(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:returns: the size of the value at the position idx in the stack
:remarks: this function only works with strings, arrays, tables, classes, instances, and userdata if the value is not a valid type, the function will return -1.
returns the size of a value at the idx position in the stack. If the value is a class or a class instance the size returned is the size of the userdata buffer (see sq_setclassudsize).
.. _sq_getstring:
.. c:function:: SQRESULT sq_getstring(HSQUIRRELVM v, SQInteger idx, const SQChar ** c)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param const SQChar ** c: a pointer to the pointer that will point to the string
:returns: a SQRESULT
gets a pointer to the string at the idx position in the stack.
.. _sq_getstringandsize:
.. c:function:: SQRESULT sq_getstringandsize(HSQUIRRELVM v, SQInteger idx, const SQChar ** c, SQInteger* size)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param const SQChar ** c: a pointer to the pointer that will point to the string
:param SQInteger * size: a pointer to a SQInteger which will receive the size of the string
:returns: a SQRESULT
gets a pointer to the string at the idx position in the stack; additionally retrieves its size.
.. _sq_getthread:
.. c:function:: SQRESULT sq_getthread(HSQUIRRELVM v, SQInteger idx, HSQUIRRELVM* v)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param HSQUIRRELVM* v: A pointer to the variable that will store the thread pointer
:returns: a SQRESULT
gets a pointer to the thread the idx position in the stack.
.. _sq_gettype:
.. c:function:: SQObjectType sq_gettype(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:returns: the type of the value at the position idx in the stack
returns the type of the value at the position idx in the stack
.. _sq_gettypetag:
.. c:function:: SQRESULT sq_gettypetag(HSQUIRRELVM v, SQInteger idx, SQUserPointer * typetag)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQUserPointer * typetag: a pointer to the variable that will store the tag
:returns: a SQRESULT
:remarks: the function works also with instances. if the taget object is an instance, the typetag of it's base class is fetched.
gets the typetag of the object (userdata or class) at position idx in the stack.
.. _sq_getuserdata:
.. c:function:: SQRESULT sq_getuserdata(HSQUIRRELVM v, SQInteger idx, SQUserPointer * p, SQUserPointer * typetag)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQUserPointer * p: A pointer to the userpointer that will point to the userdata's payload
:param SQUserPointer * typetag: A pointer to a SQUserPointer that will store the userdata tag(see sq_settypetag). The parameter can be NULL.
:returns: a SQRESULT
gets a pointer to the value of the userdata at the idx position in the stack.
.. _sq_getuserpointer:
.. c:function:: SQRESULT sq_getuserpointer(HSQUIRRELVM v, SQInteger idx, SQUserPointer * p)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQUserPointer * p: A pointer to the userpointer that will store the value
:returns: a SQRESULT
gets the value of the userpointer at the idx position in the stack.
.. _sq_newarray:
.. c:function:: void sq_newarray(HSQUIRRELVM v, SQInteger size)
:param HSQUIRRELVM v: the target VM
:param SQInteger size: the size of the array that as to be created
creates a new array and pushes it in the stack
.. _sq_newclass:
.. c:function:: SQRESULT sq_newclass(HSQUIRRELVM v, SQBool hasbase)
:param HSQUIRRELVM v: the target VM
:param SQBool hasbase: if the parameter is true the function expects a base class on top of the stack.
:returns: a SQRESULT
creates a new class object. If the parameter 'hasbase' is different than 0, the function pops a class from the stack and inherits the new created class from it. The new class is pushed in the stack.
.. _sq_newclosure:
.. c:function:: void sq_newclosure(HSQUIRRELVM v, HSQFUNCTION func, SQInteger nfreevars)
:param HSQUIRRELVM v: the target VM
:param HSQFUNCTION func: a pointer to a native-function
:param SQInteger nfreevars: number of free variables(can be 0)
create a new native closure, pops n values set those as free variables of the new closure, and push the new closure in the stack.
.. _sq_newtable:
.. c:function:: void sq_newtable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
creates a new table and pushes it in the stack
.. _sq_newtableex:
.. c:function:: void sq_newtableex(HSQUIRRELVM v, SQInteger initialcapacity)
:param HSQUIRRELVM v: the target VM
:param SQInteger initialcapacity: number of key/value pairs to preallocate
creates a new table and pushes it in the stack. This function allows you to specify the initial capacity of the table to prevent unnecessary rehashing when the number of slots required is known at creation-time.
.. _sq_newuserdata:
.. c:function:: SQUserPointer sq_newuserdata(HSQUIRRELVM v, SQUnsignedInteger size)
:param HSQUIRRELVM v: the target VM
:param SQUnsignedInteger size: the size of the userdata that as to be created in bytes
creates a new userdata and pushes it in the stack
.. _sq_pushbool:
.. c:function:: void sq_pushbool(HSQUIRRELVM v, SQBool b)
:param HSQUIRRELVM v: the target VM
:param SQBool b: the bool that has to be pushed(SQTrue or SQFalse)
pushes a bool into the stack
.. _sq_pushfloat:
.. c:function:: void sq_pushfloat(HSQUIRRELVM v, SQFloat f)
:param HSQUIRRELVM v: the target VM
:param SQFloat f: the float that has to be pushed
pushes a float into the stack
.. _sq_pushinteger:
.. c:function:: void sq_pushinteger(HSQUIRRELVM v, SQInteger n)
:param HSQUIRRELVM v: the target VM
:param SQInteger n: the integer that has to be pushed
pushes an integer into the stack
.. _sq_pushnull:
.. c:function:: void sq_pushnull(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pushes a null value into the stack
.. _sq_pushstring:
.. c:function:: void sq_pushstring(HSQUIRRELVM v, const SQChar * s, SQInteger len)
:param HSQUIRRELVM v: the target VM
:param const SQChar * s: pointer to the string that has to be pushed
:param SQInteger len: length of the string pointed by s
:remarks: if the parameter len is less than 0 the VM will calculate the length using strlen(s)
pushes a string in the stack
.. _sq_pushuserpointer:
.. c:function:: void sq_pushuserpointer(HSQUIRRELVM v, SQUserPointer p)
:param HSQUIRRELVM v: the target VM
:param SQUserPointer p: the pointer that as to be pushed
pushes a userpointer into the stack
.. _sq_setbyhandle:
.. c:function:: SQRESULT sq_setbyhandle(HSQUIRRELVM v, SQInteger idx, HSQMEMBERHANDLE* handle)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack pointing to the class
:param HSQMEMBERHANDLE* handle: a pointer the member handle
:returns: a SQRESULT
pops a value from the stack and sets it to a class or instance member using a member handle (see sq_getmemberhandle)
.. _sq_setclassudsize:
.. c:function:: SQRESULT sq_setclassudsize(HSQUIRRELVM v, SQInteger idx, SQInteger udsize)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack pointing to the class
:param SQInteger udsize: size in bytes reserved for user data
:returns: a SQRESULT
Sets the user data size of a class. If a class 'user data size' is greater than 0. When an instance of the class is created additional space will be reserved at the end of the memory chunk where the instance is stored. The userpointer of the instance will also be automatically set to this memory area. This allows you to minimize allocations in applications that have to carry data along with the class instance.
.. _sq_setclosureroot:
.. c:function:: SQRESULT sq_setclosureroot(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target closure
:returns: an SQRESULT
pops a table from the stack and sets it as root of the closure at position idx in the stack
.. _sq_setinstanceup:
.. c:function:: SQRESULT sq_setinstanceup(HSQUIRRELVM v, SQInteger idx, SQUserPointer up)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQUserPointer up: an arbitrary user pointer
:returns: a SQRESULT
sets the userpointer of the class instance at position idx in the stack.
.. _sq_setnativeclosurename:
.. c:function:: SQRESULT sq_setnativeclosurename(HSQUIRRELVM v, SQInteger idx, const SQChar * name)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target native closure
:param const SQChar * name: the name that has to be set
:returns: an SQRESULT
sets the name of the native closure at the position idx in the stack. The name of a native closure is purely for debug purposes. The name is retrieved through the function sq_stackinfos() while the closure is in the call stack.
.. _sq_setparamscheck:
.. c:function:: SQRESULT sq_setparamscheck(HSQUIRRELVM v, SQInteger nparamscheck, const SQChar * typemask)
:param HSQUIRRELVM v: the target VM
:param SQInteger nparamscheck: defines the parameters number check policy (0 disables the param checking). If nparamscheck is greater than 0, the VM ensures that the number of parameters is exactly the number specified in nparamscheck (eg. if nparamscheck == 3 the function can only be called with 3 parameters). If nparamscheck is less than 0 the VM ensures that the closure is called with at least the absolute value of the number specified in nparamcheck (eg. nparamscheck == -3 will check that the function is called with at least 3 parameters). The hidden parameter 'this' is included in this number; free variables aren't. If SQ_MATCHTYPEMASKSTRING is passed instead of the number of parameters, the function will automatically infer the number of parameters to check from the typemask (eg. if the typemask is ".sn", it is like passing 3).
:param const SQChar * typemask: defines a mask to validate the parametes types passed to the function. If the parameter is NULL, no typechecking is applied (default).
:remarks: The typemask consists in a zero terminated string that represent the expected parameter type. The types are expressed as follows: 'o' null, 'i' integer, 'f' float, 'n' integer or float, 's' string, 't' table, 'a' array, 'u' userdata, 'c' closure and nativeclosure, 'g' generator, 'p' userpointer, 'v' thread, 'x' instance(class instance), 'y' class, 'b' bool. and '.' any type. The symbol '|' can be used as 'or' to accept multiple types on the same parameter. There isn't any limit on the number of 'or' that can be used. Spaces are ignored so can be inserted between types to increase readability. For instance to check a function that expect a table as 'this' a string as first parameter and a number or a userpointer as second parameter, the string would be "tsn|p" (table,string,number or userpointer). If the parameters mask is contains fewer parameters than 'nparamscheck', the remaining parameters will not be typechecked.
Sets the parameter validation scheme for the native closure at the top position in the stack. Allows you to validate the number of parameters accepted by the function and optionally their types. If the function call does not comply with the parameter schema set by sq_setparamscheck, an exception is thrown.
*.eg*
::
//example
SQInteger testy(HSQUIRRELVM v)
{
SQUserPointer p;
const SQChar *s;
SQInteger i;
//no type checking, if the call complies with the mask
//surely the functions will succeed.
sq_getuserdata(v,1,&p,NULL);
sq_getstring(v,2,&s);
sq_getinteger(v,3,&i);
//... do something
return 0;
}
//the reg code
//....stuff
sq_newclosure(v,testy,0);
//expects exactly 3 parameters(userdata,string,number)
sq_setparamscheck(v,3,_SC("usn"));
//....stuff
.. _sq_setreleasehook:
.. c:function:: void sq_setreleasehook(HSQUIRRELVM v, SQInteger idx, SQRELEASEHOOK hook)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQRELEASEHOOK hook: a function pointer to the hook(see sample below)
:remarks: the function hook is called by the VM before the userdata memory is deleted.
sets the release hook of the userdata, class instance, or class at position idx in the stack.
*.eg*
::
/* tyedef SQInteger (*SQRELEASEHOOK)(SQUserPointer,SQInteger size); */
SQInteger my_release_hook(SQUserPointer p,SQInteger size)
{
/* do something here */
return 1;
}
.. _sq_settypetag:
.. c:function:: SQRESULT sq_settypetag(HSQUIRRELVM v, SQInteger idx, SQUserPointer typetag)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQUserPointer typetag: an arbitrary SQUserPointer
:returns: a SQRESULT
sets the typetag of the object (userdata or class) at position idx in the stack.
.. _sq_tobool:
.. c:function:: void sq_tobool(HSQUIRRELVM v, SQInteger idx, SQBool * b)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:param SQBool * b: A pointer to the bool that will store the value
:remarks: if the object is not a bool the function converts the value to bool according to squirrel's rules. For instance the number 1 will result in true, and the number 0 in false.
gets the value at position idx in the stack as bool.
.. _sq_tostring:
.. c:function:: void sq_tostring(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
converts the object at position idx in the stack to string and pushes the resulting string in the stack.
.. _sq_typeof:
.. c:function:: SQObjectType sq_typeof(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: an index in the stack
:returns: a SQRESULT
pushes the type name of the value at the position idx in the stack. It also invokes the _typeof metamethod for tables and class instances that implement it; in that case the pushed object could be something other than a string (is up to the _typeof implementation).

View File

@ -0,0 +1,451 @@
.. _api_ref_object_manipulation:
====================
Object manipulation
====================
.. _sq_arrayappend:
.. c:function:: SQRESULT sq_arrayappend(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target array in the stack
:returns: a SQRESULT
:remarks: Only works on arrays.
pops a value from the stack and pushes it in the back of the array at the position idx in the stack.
.. _sq_arrayinsert:
.. c:function:: SQRESULT sq_arrayinsert(HSQUIRRELVM v, SQInteger idx, SQInteger destpos)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target array in the stack
:param SQInteger destpos: the position in the array where the item has to be inserted
:returns: a SQRESULT
:remarks: Only works on arrays.
pops a value from the stack and inserts it in an array at the specified position
.. _sq_arraypop:
.. c:function:: SQRESULT sq_arraypop(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target array in the stack
:returns: a SQRESULT
:remarks: Only works on arrays.
pops a value from the back of the array at the position idx in the stack.
.. _sq_arrayremove:
.. c:function:: SQRESULT sq_arrayremove(HSQUIRRELVM v, SQInteger idx, SQInteger itemidx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target array in the stack
:param SQInteger itemidx: the index of the item in the array that has to be removed
:returns: a SQRESULT
:remarks: Only works on arrays.
removes an item from an array
.. _sq_arrayresize:
.. c:function:: SQRESULT sq_arrayresize(HSQUIRRELVM v, SQInteger idx, SQInteger newsize)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target array in the stack
:param SQInteger newsize: requested size of the array
:returns: a SQRESULT
:remarks: Only works on arrays. If newsize if greater than the current size the new array slots will be filled with nulls.
resizes the array at the position idx in the stack.
.. _sq_arrayreverse:
.. c:function:: SQRESULT sq_arrayreverse(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target array in the stack
:returns: a SQRESULT
:remarks: Only works on arrays.
reverses an array in place.
.. _sq_clear:
.. c:function:: SQRESULT sq_clear(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
:remarks: Only works on tables and arrays.
clears all the elements of the table/array at position idx in the stack.
.. _sq_clone:
.. c:function:: SQRESULT sq_clone(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
pushes a clone of the table, array, or class instance at the position idx.
.. _sq_createslot:
.. c:function:: SQRESULT sq_createslot(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target table in the stack
:returns: a SQRESULT
:remarks: invoke the _newslot metamethod in the table delegate. it only works on tables. [this function is deperecated since version 2.0.5 use sq_newslot() instead]
pops a key and a value from the stack and performs a set operation on the table or class that is at position idx in the stack; if the slot does not exist, it will be created.
.. _sq_deleteslot:
.. c:function:: SQRESULT sq_deleteslot(HSQUIRRELVM v, SQInteger idx, SQBool pushval)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target table in the stack
:param SQBool pushval: if this param is true the function will push the value of the deleted slot.
:returns: a SQRESULT
:remarks: invoke the _delslot metamethod in the table delegate. it only works on tables.
pops a key from the stack and delete the slot indexed by it from the table at position idx in the stack; if the slot does not exist, nothing happens.
.. _sq_get:
.. c:function:: SQRESULT sq_get(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
:remarks: this call will invokes the delegation system like a normal dereference it only works on tables, arrays, classes, instances and userdata; if the function fails, nothing will be pushed in the stack.
pops a key from the stack and performs a get operation on the object at the position idx in the stack; and pushes the result in the stack.
.. _sq_getattributes:
.. c:function:: SQRESULT sq_getattributes(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target class in the stack
:returns: a SQRESULT
Gets the attribute of a class member. The function pops a key from the stack and pushes the attribute of the class member indexed by they key from a class at position idx in the stack. If key is null the function gets the class level attribute.
.. _sq_getbase:
.. c:function:: SQRESULT sq_getbase(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target class in the stack
:returns: a SQRESULT
pushes the base class of the 'class' at stored position idx in the stack.
.. _sq_getclass:
.. c:function:: SQRESULT sq_getclass(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target class instance in the stack
:returns: a SQRESULT
pushes the class of the 'class instance' at stored position idx in the stack.
.. _sq_getdelegate:
.. c:function:: SQRESULT sq_getdelegate(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
pushes the current delegate of the object at the position idx in the stack.
.. _sq_getfreevariable:
.. c:function:: const SQChar * sq_getfreevariable(HSQUIRRELVM v, SQInteger idx, SQInteger nval)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack(closure)
:param SQInteger nval: 0 based index of the free variable(relative to the closure).
:returns: the name of the free variable for pure squirrel closures. NULL in case of error or if the index of the variable is out of range. In case the target closure is a native closure, the return name is always "@NATIVE".
:remarks: The function works for both squirrel closure and native closure.
gets the value of the free variable of the closure at the position idx in the stack.
.. _sq_getweakrefval:
.. c:function:: SQRESULT sq_getweakrefval(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target weak reference
:returns: a SQRESULT
:remarks: if the function fails, nothing is pushed in the stack.
pushes the object pointed by the weak reference at position idx in the stack.
.. _sq_instanceof:
.. c:function:: SQBool sq_instanceof(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: SQTrue if the instance at position -2 in the stack is an instance of the class object at position -1 in the stack.
:remarks: The function doesn't pop any object from the stack.
Determines if an object is an instance of a certain class. Expects an instance and a class in the stack.
.. _sq_newmember:
.. c:function:: SQRESULT sq_newmember(HSQUIRRELVM v, SQInteger idx, SQBool bstatic)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target table in the stack
:param SQBool bstatic: if SQTrue creates a static member.
:returns: a SQRESULT
:remarks: Invokes the _newmember metamethod in the class. it only works on classes.
pops a key, a value and an object (which will be set as attribute of the member) from the stack and performs a new slot operation on the class that is at position idx in the stack; if the slot does not exist, it will be created.
.. _sq_newslot:
.. c:function:: SQRESULT sq_newslot(HSQUIRRELVM v, SQInteger idx, SQBool bstatic)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target table in the stack
:param SQBool bstatic: if SQTrue creates a static member. This parameter is only used if the target object is a class.
:returns: a SQRESULT
:remarks: Invokes the _newslot metamethod in the table delegate. it only works on tables and classes.
pops a key and a value from the stack and performs a set operation on the table or class that is at position idx in the stack, if the slot does not exist it will be created.
.. _sq_next:
.. c:function:: SQRESULT sq_next(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
Pushes in the stack the next key and value of an array, table, or class slot. To start the iteration this function expects a null value on top of the stack; at every call the function will substitute the null value with an iterator and push key and value of the container slot. Every iteration the application has to pop the previous key and value but leave the iterator(that is used as reference point for the next iteration). The function will fail when all slots have been iterated(see Tables and arrays manipulation).
.. _sq_rawdeleteslot:
.. c:function:: SQRESULT sq_rawdeleteslot(HSQUIRRELVM v, SQInteger idx, SQBool pushval)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target table in the stack
:param SQBool pushval: if this param is true the function will push the value of the deleted slot.
:returns: a SQRESULT
Deletes a slot from a table without employing the _delslot metamethod. Pops a key from the stack and delete the slot indexed by it from the table at position idx in the stack; if the slot does not exist nothing happens.
.. _sq_rawget:
.. c:function:: SQRESULT sq_rawget(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
:remarks: Only works on tables and arrays.
pops a key from the stack and performs a get operation on the object at position idx in the stack, without employing delegation or metamethods.
.. _sq_rawnewmember:
.. c:function:: SQRESULT sq_rawnewmember(HSQUIRRELVM v, SQInteger idx, SQBool bstatic)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target table in the stack
:param SQBool bstatic: if SQTrue creates a static member.
:returns: a SQRESULT
:remarks: it only works on classes.
pops a key, a value and an object(that will be set as attribute of the member) from the stack and performs a new slot operation on the class that is at position idx in the stack; if the slot does not exist it will be created.
.. _sq_rawset:
.. c:function:: SQRESULT sq_rawset(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
:remarks: it only works on tables and arrays. if the function fails nothing will be pushed in the stack.
pops a key and a value from the stack and performs a set operation on the object at position idx in the stack, without employing delegation or metamethods.
.. _sq_set:
.. c:function:: SQRESULT sq_set(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
:remarks: this call will invoke the delegation system like a normal assignment, it only works on tables, arrays and userdata.
pops a key and a value from the stack and performs a set operation on the object at position idx in the stack.
.. _sq_setattributes:
.. c:function:: SQRESULT sq_setattributes(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target class in the stack.
:returns: a SQRESULT
Sets the attribute of a class member. The function pops a key and a value from the stack and sets the attribute (indexed by the key) on the class at position idx in the stack. If key is null the function sets the class level attribute. If the function succeed, the old attribute value is pushed in the stack.
.. _sq_setdelegate:
.. c:function:: SQRESULT sq_setdelegate(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:returns: a SQRESULT
:remarks: to remove the delegate from an object, set a null value.
pops a table from the stack and sets it as the delegate of the object at the position idx in the stack.
.. _sq_setfreevariable:
.. c:function:: SQRESULT sq_setfreevariable(HSQUIRRELVM v, SQInteger idx, SQInteger nval)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:param SQInteger nval: 0 based index of the free variable(relative to the closure).
:returns: a SQRESULT
pops a value from the stack and sets it as a free variable of the closure at the position idx in the stack.
.. _sq_weakref:
.. c:function:: void sq_weakref(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index to the target object in the stack
:returns: a SQRESULT
:remarks: if the object at idx position is one of (integer, float, bool, null), the object itself is pushed instead of a weak ref.
pushes a weak reference to the object at position idx in the stack.

View File

@ -0,0 +1,163 @@
.. _api_ref_raw_object_handling:
===================
Raw object handling
===================
.. _sq_addref:
.. c:function:: void sq_addref(HSQUIRRELVM v, HSQOBJECT* po)
:param HSQUIRRELVM v: the target VM
:param HSQOBJECT* po: pointer to an object handler
adds a reference to an object handler.
.. _sq_getobjtypetag:
.. c:function:: SQRESULT sq_getobjtypetag(HSQOBJECT* o, SQUserPointer* typetag)
:param HSQOBJECT* o: pointer to an object handler
:param SQUserPointer* typetag: a pointer to the variable that will store the tag
:returns: a SQRESULT
:remarks: the function works also with instances. if the target object is an instance, the typetag of it's base class is fetched.
gets the typetag of a raw object reference(userdata or class).
.. _sq_getrefcount:
.. c:function:: SQUnsignedInteger sq_getrefcount(HSQUIRRELVM v, HSQOBJECT* po)
:param HSQUIRRELVM v: the target VM
:param HSQOBJECT* po: object handler
returns the number of references of a given object.
.. _sq_getstackobj:
.. c:function:: SQRESULT sq_getstackobj(HSQUIRRELVM v, SQInteger idx, HSQOBJECT* po)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the target object in the stack
:param HSQOBJECT* po: pointer to an object handler
:returns: a SQRESULT
gets an object from the stack and stores it in a object handler.
.. _sq_objtobool:
.. c:function:: SQBool sq_objtobool(HSQOBJECT* po)
:param HSQOBJECT* po: pointer to an object handler
:remarks: If the object is not a bool will always return false.
return the bool value of a raw object reference.
.. _sq_objtofloat:
.. c:function:: SQFloat sq_objtofloat(HSQOBJECT* po)
:param HSQOBJECT* po: pointer to an object handler
:remarks: If the object is an integer will convert it to float. If the object is not a number will always return 0.
return the float value of a raw object reference.
.. _sq_objtointeger:
.. c:function:: SQInteger sq_objtointeger(HSQOBJECT* po)
:param HSQOBJECT* po: pointer to an object handler
:remarks: If the object is a float will convert it to integer. If the object is not a number will always return 0.
return the integer value of a raw object reference.
.. _sq_objtostring:
.. c:function:: const SQChar* sq_objtostring(HSQOBJECT* po)
:param HSQOBJECT* po: pointer to an object handler
:remarks: If the object doesn't reference a string it returns NULL.
return the string value of a raw object reference.
.. _sq_objtouserpointer:
.. c:function:: SQUserPointer sq_objtouserpointer(HSQOBJECT* po)
:param HSQOBJECT* po: pointer to an object handler
:remarks: If the object doesn't reference a userpointer it returns NULL.
return the userpointer value of a raw object reference.
.. _sq_pushobject:
.. c:function:: void sq_pushobject(HSQUIRRELVM v, HSQOBJECT obj)
:param HSQUIRRELVM v: the target VM
:param HSQOBJECT obj: object handler
push an object referenced by an object handler into the stack.
.. _sq_release:
.. c:function:: SQBool sq_release(HSQUIRRELVM v, HSQOBJECT* po)
:param HSQUIRRELVM v: the target VM
:param HSQOBJECT* po: pointer to an object handler
:returns: SQTrue if the object handler released has lost all is references(the ones added with sq_addref). SQFalse otherwise.
:remarks: the function will reset the object handler to null when it loses all references.
remove a reference from an object handler.
.. _sq_resetobject:
.. c:function:: void sq_resetobject(HSQOBJECT* po)
:param HSQOBJECT* po: pointer to an object handler
:remarks: Every object handler has to be initialized with this function.
resets(initialize) an object handler.

View File

@ -0,0 +1,107 @@
.. _api_ref_stack_operations:
================
Stack Operations
================
.. _sq_cmp:
.. c:function:: SQInteger sq_cmp(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: > 0 if obj1>obj2
:returns: == 0 if obj1==obj2
:returns: < 0 if obj1<obj2
compares 2 object from the top of the stack. obj2 should be pushed before obj1.
.. _sq_gettop:
.. c:function:: SQInteger sq_gettop(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an integer representing the index of the top of the stack
returns the index of the top of the stack
.. _sq_pop:
.. c:function:: void sq_pop(HSQUIRRELVM v, SQInteger nelementstopop)
:param HSQUIRRELVM v: the target VM
:param SQInteger nelementstopop: the number of elements to pop
pops n elements from the stack
.. _sq_poptop:
.. c:function:: void sq_poptop(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pops 1 object from the stack
.. _sq_push:
.. c:function:: void sq_push(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: the index in the stack of the value that has to be pushed
pushes in the stack the value at the index idx
.. _sq_remove:
.. c:function:: void sq_remove(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: index of the element that has to be removed
removes an element from an arbitrary position in the stack
.. _sq_reservestack:
.. c:function:: SQRESULT sq_reservestack(HSQUIRRELVM v, SQInteger nsize)
:param HSQUIRRELVM v: the target VM
:param SQInteger nsize: required stack size
:returns: a SQRESULT
ensure that the stack space left is at least of a specified size.If the stack is smaller it will automatically grow. If there's a metamethod currently running the function will fail and the stack will not be resized, this situation has to be considered a "stack overflow".
.. _sq_settop:
.. c:function:: void sq_settop(HSQUIRRELVM v, SQInteger v)
:param HSQUIRRELVM v: the target VM
:param SQInteger v: the new top index
resize the stack. If new top is bigger then the current top the function will push nulls.

View File

@ -0,0 +1,341 @@
.. _api_ref_virtual_machine:
===============
Virtual Machine
===============
.. _sq_close:
.. c:function:: void sq_close(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
releases a squirrel VM and all related friend VMs
.. _sq_geterrorfunc:
.. c:function:: SQPRINTFUNCTION sq_geterrorfunc(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: a pointer to a SQPRINTFUNCTION, or NULL if no function has been set.
returns the current error function of the given Virtual machine. (see sq_setprintfunc())
.. _sq_getforeignptr:
.. c:function:: SQUserPointer sq_getforeignptr(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: the current VMs foreign pointer.
Returns the foreign pointer of a VM instance.
.. _sq_getprintfunc:
.. c:function:: SQPRINTFUNCTION sq_getprintfunc(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: a pointer to a SQPRINTFUNCTION, or NULL if no function has been set.
returns the current print function of the given Virtual machine. (see sq_setprintfunc())
.. _sq_getsharedforeignptr:
.. c:function:: SQUserPointer sq_getsharedforeignptr(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: the current VMs shared foreign pointer
Returns the shared foreign pointer of a group of friend VMs
.. _sq_getsharedreleasehook:
.. c:function:: SQUserPointer sq_getsharedreleasehook(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: the current VMs release hook.
Returns the shared release hook of a group of friend VMs
.. _sq_getversion:
.. c:function:: SQInteger sq_getversion()
:returns: version number of the vm(as in SQUIRREL_VERSION_NUMBER).
returns the version number of the vm
.. _sq_getvmreleasehook:
.. c:function:: SQUserPointer sq_getvmreleasehook(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: the current VMs release hook.
Returns the release hook of a VM instance
.. _sq_getvmstate:
.. c:function:: SQInteger sq_getvmstate(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: the state of the vm encoded as integer value. The following constants are defined: SQ_VMSTATE_IDLE, SQ_VMSTATE_RUNNING, SQ_VMSTATE_SUSPENDED.
returns the execution state of a virtual machine
.. _sq_move:
.. c:function:: void sq_move(HSQUIRRELVM dest, HSQUIRRELVM src, SQInteger idx)
:param HSQUIRRELVM dest: the destination VM
:param HSQUIRRELVM src: the source VM
:param SQInteger idx: the index in the source stack of the value that has to be moved
pushes the object at the position 'idx' of the source vm stack in the destination vm stack
.. _sq_newthread:
.. c:function:: HSQUIRRELVM sq_newthread(HSQUIRRELVM friendvm, SQInteger initialstacksize)
:param HSQUIRRELVM friendvm: a friend VM
:param SQInteger initialstacksize: the size of the stack in slots(number of objects)
:returns: a pointer to the new VM.
:remarks: By default the roottable is shared with the VM passed as first parameter. The new VM lifetime is bound to the "thread" object pushed in the stack and behave like a normal squirrel object.
creates a new vm friendvm of the one passed as first parmeter and pushes it in its stack as "thread" object.
.. _sq_open:
.. c:function:: HSQUIRRELVM sq_open(SQInteger initialstacksize)
:param SQInteger initialstacksize: the size of the stack in slots(number of objects)
:returns: an handle to a squirrel vm
:remarks: the returned VM has to be released with sq_releasevm
creates a new instance of a squirrel VM that consists in a new execution stack.
.. _sq_pushconsttable:
.. c:function:: void sq_pushconsttable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pushes the current const table in the stack
.. _sq_pushregistrytable:
.. c:function:: void sq_pushregistrytable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pushes the registry table in the stack
.. _sq_pushroottable:
.. c:function:: void sq_pushroottable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pushes the current root table in the stack
.. _sq_setconsttable:
.. c:function:: void sq_setconsttable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pops a table from the stack and set it as const table
.. _sq_seterrorhandler:
.. c:function:: void sq_seterrorhandler(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:remarks: the error handler is shared by friend VMs
pops from the stack a closure or native closure an sets it as runtime-error handler.
.. _sq_setforeignptr:
.. c:function:: void sq_setforeignptr(HSQUIRRELVM v, SQUserPointer p)
:param HSQUIRRELVM v: the target VM
:param SQUserPointer p: The pointer that has to be set
Sets the foreign pointer of a certain VM instance. The foreign pointer is an arbitrary user defined pointer associated to a VM (by default is value id 0). This pointer is ignored by the VM.
.. _sq_setprintfunc:
.. c:function:: void sq_setprintfunc(HSQUIRRELVM v, SQPRINTFUNCTION printfunc, SQPRINTFUNCTION errorfunc)
:param HSQUIRRELVM v: the target VM
:param SQPRINTFUNCTION printfunc: a pointer to the print func or NULL to disable the output.
:param SQPRINTFUNCTION errorfunc: a pointer to the error func or NULL to disable the output.
:remarks: the print func has the following prototype: void printfunc(HSQUIRRELVM v,const SQChar \*s,...)
sets the print function of the virtual machine. This function is used by the built-in function '::print()' to output text.
.. _sq_setroottable:
.. c:function:: void sq_setroottable(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
pops a table from the stack and set it as root table
.. _sq_setsharedforeignptr:
.. c:function:: void sq_setsharedforeignptr(HSQUIRRELVM v, SQUserPointer p)
:param HSQUIRRELVM v: the target VM
:param SQUserPointer p: The pointer that has to be set
Sets the shared foreign pointer. The foreign pointer is an arbitrary user defined pointer associated to a group of friend VMs (by default is value id 0). After a "main" VM is created using sq_open() all friend VMs created with sq_newthread share the same shared pointer.
.. _sq_setsharedreleasehook:
.. c:function:: void sq_setsharedreleasehook(HSQUIRRELVM v, SQRELESEHOOK hook)
:param HSQUIRRELVM v: the target VM
:param SQRELESEHOOK hook: The hook that has to be set
Sets the release hook of a certain VM group. The release hook is invoked when the last vm of the group vm is destroyed (usually when sq_close() is invoked). The userpointer passed to the function is the shared foreignpointer(see sq_getsharedforeignptr()). After a "main" VM is created using sq_open() all friend VMs created with sq_newthread() share the same shared release hook.
.. _sq_setvmreleasehook:
.. c:function:: void sq_setvmreleasehook(HSQUIRRELVM v, SQRELESEHOOK hook)
:param HSQUIRRELVM v: the target VM
:param SQRELESEHOOK hook: The hook that has to be set
Sets the release hook of a certain VM instance. The release hook is invoked when the vm is destroyed. The userpointer passed to the function is the vm foreignpointer (see sq_setforeignpointer())
.. _sq_suspendvm:
.. c:function:: HRESULT sq_suspendvm(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an SQRESULT(that has to be returned by a C function)
:remarks: sq_result can only be called as return expression of a C function. The function will fail is the suspension is done through more C calls or in a metamethod.
Suspends the execution of the specified vm.
*.eg*
::
SQInteger suspend_vm_example(HSQUIRRELVM v)
{
return sq_suspendvm(v);
}
.. _sq_wakeupvm:
.. c:function:: HRESULT sq_wakeupvm(HSQUIRRELVM v, SQBool resumedret, SQBool retval, SQBool raiseerror, SQBool throwerror)
:param HSQUIRRELVM v: the target VM
:param SQBool resumedret: if true the function will pop a value from the stack and use it as return value for the function that has previously suspended the virtual machine.
:param SQBool retval: if true the function will push the return value of the function that suspend the excution or the main function one.
:param SQBool raiseerror: if true, if a runtime error occurs during the execution of the call, the vm will invoke the error handler.
:param SQBool throwerror: if true, the vm will thow an exception as soon as is resumed. the exception payload must be set beforehand invoking sq_thowerror().
:returns: an HRESULT.
wake up the execution a previously suspended virtual machine

View File

@ -0,0 +1,18 @@
.. _api_reference:
*************
API Reference
*************
.. toctree::
api/virtual_machine.rst
api/compiler.rst
api/stack_operations.rst
api/object_creation_and_handling.rst
api/calls.rst
api/object_manipulation.rst
api/bytecode_serialization.rst
api/raw_object_handling.rst
api/garbage_collector.rst
api/debug_interface.rst

View File

@ -0,0 +1,59 @@
.. _embedding_build_configuration:
========================
Build Configuration
========================
.. _unicode:
----------
Unicode
----------
.. index:: single: Unicode
By default Squirrel strings are plain 8-bits ASCII characters; however if the symbol
'SQUNICODE' is defined the VM, compiler and API will use 16-bit characters (UCS2).
.. _squirrel_64bits:
--------------------------------
Squirrel on 64-bit architectures
--------------------------------
.. index::
single: Squirrel on 64-bit architectures
single: 64 bits
Squirrel can be compiled on 64-bit architectures by defining '_SQ64' in the C++
preprocessor. This flag should be defined in any project that includes 'squirrel.h'.
.. _userdata_alignment:
------------------
Userdata Alignment
------------------
.. index:: single: Userdata Alignment
Both class instances and userdatas can have a buffer associated to them.
Squirrel specifies the alignment(in bytes) through the preprocessor defining 'SQ_ALIGNMENT'.
By default SQ_ALIGNMENT is defined as 4 for 32-bit builds and 8 for 64-bit builds and builds that use 64-bit floats.
It is possible to override the value of SQ_ALIGNMENT respecting the following rules.
SQ_ALIGNMENT shall be less than or equal to SQ_MALLOC alignments, and it shall be power of 2.
.. note:: This only applies for userdata allocated by the VM, specified via sq_setclassudsize() or belonging to a userdata object.
userpointers specified by the user are not affected by alignment rules.
.. _standalone_vm:
------------------------------------
Stand-alone VM without compiler
------------------------------------
.. index:: single: Stand-alone VM without compiler
Squirrel's VM can be compiled without its compiler by defining 'NO_COMPILER' in the C++ preprocessor.
When 'NO_COMPILER' is defined all function related to the compiler (eg. sq_compile) will fail. Other functions
that conditionally load precompiled bytecode or compile a file (eg. sqstd_dofile) will only work with
precompiled bytecode.

View File

@ -0,0 +1,27 @@
.. _embedding_calling_a_function:
==================
Calling a function
==================
To call a squirrel function it is necessary to push the function in the stack followed by the
parameters and then call the function sq_call.
The function will pop the parameters and push the return value if the last sq_call
parameter is > 0. ::
sq_pushroottable(v);
sq_pushstring(v,"foo",-1);
sq_get(v,-2); //get the function from the root table
sq_pushroottable(v); //'this' (function environment object)
sq_pushinteger(v,1);
sq_pushfloat(v,2.0);
sq_pushstring(v,"three",-1);
sq_call(v,4,SQFalse,SQFalse);
sq_pop(v,2); //pops the roottable and the function
this is equivalent to the following Squirrel code::
foo(1,2.0,"three");
If a runtime error occurs (or a exception is thrown) during the squirrel code execution
the sq_call will fail.

View File

@ -0,0 +1,58 @@
.. embedding_compiling_a_script:
==================
Compiling a script
==================
You can compile a Squirrel script with the function *sq_compile*.::
typedef SQInteger (*SQLEXREADFUNC)(SQUserPointer userdata);
SQRESULT sq_compile(HSQUIRRELVM v,SQLEXREADFUNC read,SQUserPointer p,
const SQChar *sourcename,SQBool raiseerror);
In order to compile a script is necessary for the host application to implement a reader
function (SQLEXREADFUNC); this function is used to feed the compiler with the script
data.
The function is called every time the compiler needs a character; It has to return a
character code if succeed or 0 if the source is finished.
If sq_compile succeeds, the compiled script will be pushed as Squirrel function in the
stack.
.. :note::
In order to execute the script, the function generated by *sq_compile()* has
to be called through *sq_call()*
Here an example of a 'read' function that read from a file: ::
SQInteger file_lexfeedASCII(SQUserPointer file)
{
int ret;
char c;
if( ( ret=fread(&c,sizeof(c),1,(FILE *)file )>0) )
return c;
return 0;
}
int compile_file(HSQUIRRELVM v,const char *filename)
{
FILE *f=fopen(filename,"rb");
if(f)
{
sq_compile(v,file_lexfeedASCII,f,filename,1);
fclose(f);
return 1;
}
return 0;
}
When the compiler fails for a syntax error it will try to call the 'compiler error handler';
this function must be declared as follow: ::
typedef void (*SQCOMPILERERROR)(HSQUIRRELVM /*v*/,const SQChar * /*desc*/,const SQChar * /*source*/,
SQInteger /*line*/,SQInteger /*column*/);
and can be set with the following API call::
void sq_setcompilererrorhandler(HSQUIRRELVM v,SQCOMPILERERROR f);

View File

@ -0,0 +1,106 @@
.. _embedding_creating_a_c_function:
===================
Create a C function
===================
A native C function must have the following prototype: ::
typedef SQInteger (*SQFUNCTION)(HSQUIRRELVM);
The parameters is an handle to the calling VM and the return value is an integer
respecting the following rules:
* 1 if the function returns a value
* 0 if the function does not return a value
* SQ_ERROR runtime error is thrown
In order to obtain a new callable squirrel function from a C function pointer, is necessary
to call sq_newclosure() passing the C function to it; the new Squirrel function will be
pushed in the stack.
When the function is called, the stackbase is the first parameter of the function and the
top is the last. In order to return a value the function has to push it in the stack and
return 1.
Function parameters are in the stack from position 1 ('this') to *n*.
*sq_gettop()* can be used to determinate the number of parameters.
If the function has free variables, those will be in the stack after the explicit parameters
an can be handled as normal parameters. Note also that the value returned by *sq_gettop()* will be
affected by free variables. *sq_gettop()* will return the number of parameters plus
number of free variables.
Here an example, the following function print the value of each argument and return the
number of arguments. ::
SQInteger print_args(HSQUIRRELVM v)
{
SQInteger nargs = sq_gettop(v); //number of arguments
for(SQInteger n=1;n<=nargs;n++)
{
printf("arg %d is ",n);
switch(sq_gettype(v,n))
{
case OT_NULL:
printf("null");
break;
case OT_INTEGER:
printf("integer");
break;
case OT_FLOAT:
printf("float");
break;
case OT_STRING:
printf("string");
break;
case OT_TABLE:
printf("table");
break;
case OT_ARRAY:
printf("array");
break;
case OT_USERDATA:
printf("userdata");
break;
case OT_CLOSURE:
printf("closure(function)");
break;
case OT_NATIVECLOSURE:
printf("native closure(C function)");
break;
case OT_GENERATOR:
printf("generator");
break;
case OT_USERPOINTER:
printf("userpointer");
break;
case OT_CLASS:
printf("class");
break;
case OT_INSTANCE:
printf("instance");
break;
case OT_WEAKREF:
printf("weak reference");
break;
default:
return sq_throwerror(v,"invalid param"); //throws an exception
}
}
printf("\n");
sq_pushinteger(v,nargs); //push the number of arguments as return value
return 1; //1 because 1 value is returned
}
Here an example of how to register a function::
SQInteger register_global_func(HSQUIRRELVM v,SQFUNCTION f,const char *fname)
{
sq_pushroottable(v);
sq_pushstring(v,fname,-1);
sq_newclosure(v,f,0); //create a new function
sq_newslot(v,-3,SQFalse);
sq_pop(v,1); //pops the root table
return 0;
}

View File

@ -0,0 +1,58 @@
.. _embedding_debug_interface:
===============
Debug Interface
===============
The squirrel VM exposes a very simple debug interface that allows to easily built a full
featured debugger.
Through the functions sq_setdebughook and sq_setnativedebughook is possible in fact to set a callback function that
will be called every time the VM executes an new line of a script or if a function get
called/returns. The callback will pass as argument the current line the current source and the
current function name (if any).::
SQUIRREL_API void sq_setdebughook(HSQUIRRELVM v);
or ::
SQUIRREL_API void sq_setnativedebughook(HSQUIRRELVM v,SQDEBUGHOOK hook);
The following code shows how a debug hook could look like(obviously is possible to
implement this function in C as well). ::
function debughook(event_type,sourcefile,line,funcname)
{
local fname=funcname?funcname:"unknown";
local srcfile=sourcefile?sourcefile:"unknown"
switch (event_type) {
case 'l': //called every line(that contains some code)
::print("LINE line [" + line + "] func [" + fname + "]");
::print("file [" + srcfile + "]\n");
break;
case 'c': //called when a function has been called
::print("LINE line [" + line + "] func [" + fname + "]");
::print("file [" + srcfile + "]\n");
break;
case 'r': //called when a function returns
::print("LINE line [" + line + "] func [" + fname + "]");
::print("file [" + srcfile + "]\n");
break;
}
}
The parameter *event_type* can be 'l' ,'c' or 'r' ; a hook with a 'l' event is called for each line that
gets executed, 'c' every time a function gets called and 'r' every time a function returns.
A full-featured debugger always allows displaying local variables and calls stack.
The call stack information are retrieved through sq_getstackinfos()::
SQInteger sq_stackinfos(HSQUIRRELVM v,SQInteger level,SQStackInfos *si);
While the local variables info through sq_getlocal()::
SQInteger sq_getlocal(HSQUIRRELVM v,SQUnsignedInteger level,SQUnsignedInteger nseq);
In order to receive line callbacks the scripts have to be compiled with debug infos enabled
this is done through sq_enabledebuginfo(); ::
void sq_enabledebuginfo(HSQUIRRELVM v, SQInteger debuginfo);

View File

@ -0,0 +1,16 @@
.. _embedding_error_convetions:
========================
Error Conventions
========================
.. index::
single: Error Conventions
Most of the functions in the API return a SQRESULT value; SQRESULT indicates if a
function completed successfully or not.
The macros SQ_SUCCEEDED() and SQ_FAILED() are used to test the result of a function.::
if(SQ_FAILED(sq_getstring(v,-1,&s)))
printf("getstring failed");

View File

@ -0,0 +1,28 @@
.. _embedding_memory_management:
========================
Memory Management
========================
.. index:: single: Memory Management
Squirrel uses reference counting (RC) as primary system for memory management;
however, the virtual machine (VM) has an auxiliary
mark and sweep garbage collector that can be invoked on demand.
There are 2 possible compile time options:
* The default configuration consists in RC plus a mark and sweep garbage collector.
The host program can call the function sq_collectgarbage() and perform a garbage collection cycle
during the program execution. The garbage collector isn't invoked by the VM and has to
be explicitly called by the host program.
* The second a situation consists in RC only(define NO_GARBAGE_COLLECTOR); in this case is impossible for
the VM to detect reference cycles, so is the programmer that has to solve them explicitly in order to
avoid memory leaks.
The only advantage introduced by the second option is that saves 2 additional
pointers that have to be stored for each object in the default configuration with
garbage collector(8 bytes for 32 bits systems).
The types involved are: tables, arrays, functions, threads, userdata and generators; all other
types are untouched. These options do not affect execution speed.

View File

@ -0,0 +1,21 @@
.. embedding_references_from_c:
========================================================
Mantaining references to Squirrel values from the C API
========================================================
Squirrel allows to reference values through the C API; the function sq_getstackobj() gets
a handle to a squirrel object(any type). The object handle can be used to control the lifetime
of an object by adding or removing references to it( see sq_addref() and sq_release()).
The object can be also re-pushed in the VM stack using sq_pushobject().::
HSQOBJECT obj;
sq_resetobject(&obj); //initialize the handle
sq_getstackobj(v,-2,&obj); //retrieve an object handle from the pos -2
sq_addref(v,&obj); //adds a reference to the object
... //do stuff
sq_pushobject(v,obj); //push the object in the stack
sq_release(v,&obj); //relese the object

View File

@ -0,0 +1,17 @@
.. _embedding_runtime_error_handling:
======================
Runtime error handling
======================
When an exception is not handled by Squirrel code with a try/catch statement, a runtime
error is raised and the execution of the current program is interrupted. It is possible to
set a call back function to intercept the runtime error from the host program; this is
useful to show meaningful errors to the script writer and for implementing visual
debuggers.
The following API call pops a Squirrel function from the stack and sets it as error handler.::
SQUIRREL_API void sq_seterrorhandler(HSQUIRRELVM v);
The error handler is called with 2 parameters, an environment object (this) and a object.
The object can be any squirrel type.

View File

@ -0,0 +1,70 @@
.. _embedding_tables_and_arrays_manipulation:
==============================
Tables and arrays manipulation
==============================
A new table is created calling sq_newtable, this function pushes a new table in the stack.::
void sq_newtable(HSQUIRRELVM v);
To create a new slot::
SQRESULT sq_newslot(HSQUIRRELVM v,SQInteger idx,SQBool bstatic);
To set or get the table delegate::
SQRESULT sq_setdelegate(HSQUIRRELVM v,SQInteger idx);
SQRESULT sq_getdelegate(HSQUIRRELVM v,SQInteger idx);
A new array is created calling sq_newarray, the function pushes a new array in the
stack; if the parameters size is bigger than 0 the elements are initialized to null.::
void sq_newarray (HSQUIRRELVM v,SQInteger size);
To append a value to the back of the array::
SQRESULT sq_arrayappend(HSQUIRRELVM v,SQInteger idx);
To remove a value from the back of the array::
SQRESULT sq_arraypop(HSQUIRRELVM v,SQInteger idx,SQInteger pushval);
To resize the array::
SQRESULT sq_arrayresize(HSQUIRRELVM v,SQInteger idx,SQInteger newsize);
To retrieve the size of a table or an array you must use sq_getsize()::
SQInteger sq_getsize(HSQUIRRELVM v,SQInteger idx);
To set a value in an array or table::
SQRESULT sq_set(HSQUIRRELVM v,SQInteger idx);
To get a value from an array or table::
SQRESULT sq_get(HSQUIRRELVM v,SQInteger idx);
To get or set a value from a table without employing delegation::
SQRESULT sq_rawget(HSQUIRRELVM v,SQInteger idx);
SQRESULT sq_rawset(HSQUIRRELVM v,SQInteger idx);
To iterate a table or an array::
SQRESULT sq_next(HSQUIRRELVM v,SQInteger idx);
Here an example of how to perform an iteration: ::
//push your table/array here
sq_pushnull(v) //null iterator
while(SQ_SUCCEEDED(sq_next(v,-2)))
{
//here -1 is the value and -2 is the key
sq_pop(v,2); //pops key and val before the nex iteration
}
sq_pop(v,1); //pops the null iterator

View File

@ -0,0 +1,14 @@
.. _embedding_the_registry_table:
==================
The registry table
==================
The registry table is an hidden table shared between vm and all his thread(friend vms).
This table is accessible only through the C API and is meant to be an utility structure
for native C library implementation.
For instance the sqstdlib(squirrel standard library)uses it to store configuration and shared objects
delegates.
The registry is accessible through the API call *sq_pushregistrytable()*.::
void sq_pushregistrytable(HSQUIRRELVM v);

View File

@ -0,0 +1,104 @@
.. _embedding_the_stack:
==========
The Stack
==========
Squirrel exchanges values with the virtual machine through a stack. This mechanism has
been inherited from the language Lua.
For instance to call a Squirrel function from C it is necessary to push the function and the
arguments in the stack and then invoke the function; also when Squirrel calls a C
function the parameters will be in the stack as well.
-------------
Stack indexes
-------------
Many API functions can arbitrarily refer to any element in the stack through an index.
The stack indexes follow those conventions:
* 1 is the stack base
* Negative indexes are considered an offset from top of the stack. For instance -1 isthe top of the stack.
* 0 is an invalid index
Here an example (let's pretend that this table is the VM stack)
+------------+--------------------+--------------------+
| **STACK** | **positive index** | **negative index** |
+============+====================+====================+
| "test" | 4 | -1(top) |
+------------+--------------------+--------------------+
| 1 | 3 | -2 |
+------------+--------------------+--------------------+
| 0.5 | 2 | -3 |
+------------+--------------------+--------------------+
| "foo" | 1(base) | -4 |
+------------+--------------------+--------------------+
In this case, the function *sq_gettop* would return 4;
------------------
Stack manipulation
------------------
The API offers several functions to push and retrieve data from the Squirrel stack.
To push a value that is already present in the stack in the top position::
void sq_push(HSQUIRRELVM v,SQInteger idx);
To pop an arbitrary number of elements::
void sq_pop(HSQUIRRELVM v,SQInteger nelemstopop);
To remove an element from the stack::
void sq_remove(HSQUIRRELVM v,SQInteger idx);
To retrieve the top index (and size) of the current
virtual stack you must call *sq_gettop* ::
SQInteger sq_gettop(HSQUIRRELVM v);
To force the stack to a certain size you can call *sq_settop* ::
void sq_settop(HSQUIRRELVM v,SQInteger newtop);
If the newtop is bigger than the previous one, the new positions in the stack will be
filled with null values.
The following function pushes a C value into the stack::
void sq_pushstring(HSQUIRRELVM v,const SQChar *s,SQInteger len);
void sq_pushfloat(HSQUIRRELVM v,SQFloat f);
void sq_pushinteger(HSQUIRRELVM v,SQInteger n);
void sq_pushuserpointer(HSQUIRRELVM v,SQUserPointer p);
void sq_pushbool(HSQUIRRELVM v,SQBool b);
this function pushes a null into the stack::
void sq_pushnull(HSQUIRRELVM v);
returns the type of the value in a arbitrary position in the stack::
SQObjectType sq_gettype(HSQUIRRELVM v,SQInteger idx);
the result can be one of the following values: ::
OT_NULL,OT_INTEGER,OT_FLOAT,OT_STRING,OT_TABLE,OT_ARRAY,OT_USERDATA,
OT_CLOSURE,OT_NATIVECLOSURE,OT_GENERATOR,OT_USERPOINTER,OT_BOOL,OT_INSTANCE,OT_CLASS,OT_WEAKREF
The following functions convert a squirrel value in the stack to a C value::
SQRESULT sq_getstring(HSQUIRRELVM v,SQInteger idx,const SQChar **c);
SQRESULT sq_getstringandsize(HSQUIRRELVM v,SQInteger idx,const SQChar **c,SQInteger size);
SQRESULT sq_getinteger(HSQUIRRELVM v,SQInteger idx,SQInteger *i);
SQRESULT sq_getfloat(HSQUIRRELVM v,SQInteger idx,SQFloat *f);
SQRESULT sq_getuserpointer(HSQUIRRELVM v,SQInteger idx,SQUserPointer *p);
SQRESULT sq_getuserdata(HSQUIRRELVM v,SQInteger idx,SQUserPointer *p,SQUserPointer *typetag);
SQRESULT sq_getbool(HSQUIRRELVM v,SQInteger idx,SQBool *p);
The function sq_cmp compares 2 values from the stack and returns their relation (like strcmp() in ANSI C).::
SQInteger sq_cmp(HSQUIRRELVM v);

View File

@ -0,0 +1,33 @@
.. _embedding_userdata_and_userpointers:
=========================
Userdata and UserPointers
=========================
Squirrel allows the host application put arbitrary data chunks into a Squirrel value, this is
possible through the data type userdata.::
SQUserPointer sq_newuserdata(HSQUIRRELVM v,SQUnsignedInteger size);
When the function *sq_newuserdata* is called, Squirrel allocates a new userdata with the
specified size, returns a pointer to his payload buffer and push the object in the stack; at
this point the application can do whatever it want with this memory chunk, the VM will
automatically take cake of the memory deallocation like for every other built-in type.
A userdata can be passed to a function or stored in a table slot. By default Squirrel
cannot manipulate directly userdata; however is possible to assign a delegate to it and
define a behavior like it would be a table.
Because the application would want to do something with the data stored in a userdata
object when it get deleted, is possible to assign a callback that will be called by the VM
just before deleting a certain userdata.
This is done through the API call *sq_setreleasehook*.::
typedef SQInteger (*SQRELEASEHOOK)(SQUserPointer,SQInteger size);
void sq_setreleasehook(HSQUIRRELVM v,SQInteger idx,SQRELEASEHOOK hook);
Another kind of userdata is the userpointer; this type is not a memory chunk like the
normal userdata, but just a 'void*' pointer. It cannot have a delegate and is passed by
value, so pushing a userpointer doesn't cause any memory allocation.::
void sq_pushuserpointer(HSQUIRRELVM v,SQUserPointer p);

View File

@ -0,0 +1,21 @@
.. _embedding_vm_initialization:
==============================
Virtual Machine Initialization
==============================
The first thing that a host application has to do, is create a virtual machine.
The host application can create any number of virtual machines through the function
*sq_open()*.
Every single VM that was created using *sq_open()* has to be released with the function *sq_close()* when it is no
longer needed.::
int main(int argc, char* argv[])
{
HSQUIRRELVM v;
v = sq_open(1024); //creates a VM with initial stack size 1024
//do some stuff with squirrel here
sq_close(v);
}

View File

@ -0,0 +1,29 @@
.. _embedding_squirrel:
***************************
Embedding Squirrel
***************************
*This section describes how to embed Squirrel in a host application,
C language knowledge is required to understand this part of the manual.*
Because of his nature of extension language, Squirrel's compiler and virtual machine
are implemented as C library. The library exposes a set of functions to compile scripts,
call functions, manipulate data and extend the virtual machine.
All declarations needed for embedding the language in an application are in the header file 'squirrel.h'.
.. toctree::
embedding/memory_management.rst
embedding/build_configuration.rst
embedding/error_conventions.rst
embedding/vm_initialization.rst
embedding/the_stack.rst
embedding/runtime_error_handling.rst
embedding/compiling_a_script.rst
embedding/calling_a_function.rst
embedding/creating_a_c_function.rst
embedding/tables_and_arrays_manipulation.rst
embedding/userdata_and_userpointers.rst
embedding/the_registry_table.rst
embedding/references_from_c.rst
embedding/debug_interface.rst

View File

@ -0,0 +1,34 @@
.. _reference:
#################################
Squirrel 3.1 Reference Manual
#################################
Copyright (c) 2003-2016 Alberto Demichelis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
.. toctree::
:maxdepth: 3
:numbered:
introduction.rst
language.rst
embedding_squirrel.rst
api_reference.rst

View File

@ -0,0 +1,16 @@
.. _introduction:
************
Introduction
************
.. index::
single: introduction
Squirrel is a high-level, imperative-OO programming language, designed to be a powerful
scripting tool that fits within the size, memory bandwidth, and real-time requirements of
applications like games.
Squirrel offers a wide range of features like dynamic typing, delegation, higher
order functions, generators, tail recursion, exception handling, automatic memory
management while fitting both compiler and virtual machine into about 6k lines of C++
code.

View File

@ -0,0 +1,23 @@
.. _thelanguage:
***************************
The language
***************************
.. toctree::
language/lexical_structure.rst
language/datatypes.rst
language/execution_context.rst
language/statements.rst
language/expressions.rst
language/tables.rst
language/arrays.rst
language/functions.rst
language/classes.rst
language/generators.rst
language/constants_and_enumerations.rst
language/threads.rst
language/weak_references.rst
language/delegation.rst
language/metamethods.rst
language/builtin_functions.rst

View File

@ -0,0 +1,19 @@
.. _arrays:
=================
Arrays
=================
.. index::
single: Arrays
An array is a sequence of values indexed by a integer number from 0 to the size of the
array minus 1. Arrays elements can be obtained through their index.::
local a=["I'm a string", 123]
print(typeof a[0]) //prints "string"
print(typeof a[1]) //prints "integer"
Resizing, insertion, deletion of arrays and arrays elements is done through a set of
standard functions (see :ref:`built-in functions <builtin_functions>`).

View File

@ -0,0 +1,693 @@
.. _builtin_functions:
==================
Built-in Functions
==================
.. index::
single: Built-in Functions
pair: Global Symbols; Built-in Functions
^^^^^^^^^^^^^^
Global Symbols
^^^^^^^^^^^^^^
.. js:function:: array(size,[fill])
creates and returns array of a specified size. If the optional parameter fill is specified its value will be used to fill the new array's slots. If the fill parameter is omitted, null is used instead.
.. js:function:: seterrorhandler(func)
sets the runtime error handler
.. js:function:: callee()
returns the currently running closure
.. js:function:: setdebughook(hook_func)
sets the debug hook
.. js:function:: enabledebuginfo(enable)
enable/disable the debug line information generation at compile time. enable != null enables. enable == null disables.
.. js:function:: getroottable()
returns the root table of the VM.
.. js:function:: setroottable(table)
sets the root table of the VM. And returns the previous root table.
.. js:function:: getconsttable()
returns the const table of the VM.
.. js:function:: setconsttable(table)
sets the const table of the VM; returns the previous const table.
.. js:function:: assert(exp, [message])
throws an exception if exp is null or false. Throws "assertion failed" string by default, or message if specified.
.. js:function:: print(x)
prints x to the standard output
.. js:function:: error(x)
prints x in the standard error output
.. js:function:: compilestring(string,[buffername])
compiles a string containing a squirrel script into a function and returns it::
local compiledscript=compilestring("::print(\"ciao\")");
//run the script
compiledscript();
.. js:function:: collectgarbage()
Runs the garbage collector and returns the number of reference cycles found (and deleted). This function only works on garbage collector builds.
.. js:function:: resurrectunreachable()
Runs the garbage collector and returns an array containing all unreachable object found. If no unreachable object is found, null is returned instead. This function is meant to help debugging reference cycles. This function only works on garbage collector builds.
.. js:function:: type(obj)
return the 'raw' type of an object without invoking the metamethod '_typeof'.
.. js:function:: getstackinfos(level)
returns the stack informations of a given call stack level. returns a table formatted as follow: ::
{
func="DoStuff", //function name
src="test.nut", //source file
line=10, //line number
locals = { //a table containing the local variables
a=10,
testy="I'm a string"
}
}
level = 0 is getstackinfos() itself! level = 1 is the current function, level = 2 is the caller of the current function, and so on. If the stack level doesn't exist the function returns null.
.. js:function:: newthread(threadfunc)
creates a new cooperative thread object(coroutine) and returns it
.. js:data:: _versionnumber_
integer values describing the version of VM and compiler. e.g. for Squirrel 3.0.1 this value will be 301
.. js:data:: _version_
string values describing the version of VM and compiler.
.. js:data:: _charsize_
size in bytes of the internal VM representation for characters(1 for ASCII builds 2 for UNICODE builds).
.. js:data:: _intsize_
size in bytes of the internal VM representation for integers(4 for 32bits builds 8 for 64bits builds).
.. js:data:: _floatsize_
size in bytes of the internal VM representation for floats(4 for single precision builds 8 for double precision builds).
-----------------
Default delegates
-----------------
Except null and userdata every squirrel object has a default delegate containing a set of functions to manipulate and retrieve information from the object itself.
^^^^^^^^
Integer
^^^^^^^^
.. js:function:: integer.tofloat()
convert the number to float and returns it
.. js:function:: integer.tostring()
converts the number to string and returns it
.. js:function:: integer.tointeger()
dummy function; returns the value of the integer.
.. js:function:: integer.tochar()
returns a string containing a single character represented by the integer.
.. js:function:: integer.weakref()
dummy function; returns the integer itself.
^^^^^
Float
^^^^^
.. js:function:: float.tofloat()
returns the value of the float(dummy function)
.. js:function:: float.tointeger()
converts the number to integer and returns it
.. js:function:: float.tostring()
converts the number to string and returns it
.. js:function:: float.tochar()
returns a string containing a single character represented by the integer part of the float.
.. js:function:: float.weakref()
dummy function; returns the float itself.
^^^^
Bool
^^^^
.. js:function:: bool.tofloat()
returns 1.0 for true 0.0 for false
.. js:function:: bool.tointeger()
returns 1 for true 0 for false
.. js:function:: bool.tostring()
returns "true" for true and "false" for false
.. js:function:: bool.weakref()
dummy function; returns the bool itself.
^^^^^^
String
^^^^^^
.. js:function:: string.len()
returns the string length
.. js:function:: 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.
.. js:function:: string.tofloat()
converts the string to float and returns it
.. js:function:: string.tostring()
returns the string (really, a dummy function)
.. js: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.
.. js:function:: string.find(substr,[startidx])
Searches a sub string (substr) starting from the index startidx and returns the index 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.
.. js:function:: string.tolower()
returns a lowercase copy of the string.
.. js:function:: string.toupper()
returns a uppercase copy of the string.
.. js:function:: string.weakref()
returns a weak reference to the object.
^^^^^
Table
^^^^^
.. js:function:: table.len()
returns the number of slots contained in a table
.. js:function:: table.rawget(key)
tries to get a value from the slot 'key' without employing delegation
.. js:function:: 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.
.. js:function:: table.rawdelete()
Deletes the slot key without employing delegation and returns its value. If the slot does not exists, returns null.
.. js:function:: 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.
.. js:function:: table.weakref()
returns a weak reference to the object.
.. js:function:: table.tostring()
Tries to invoke the _tostring metamethod. If that fails, it returns "(table : pointer)".
.. js:function:: table.clear()
removes all the slots from the table. Returns table itself.
.. js:function:: table.setdelegate(table)
Sets the delegate of the table. To remove a delegate, 'null' must be passed to the function. The function returns the table itself (e.g. a.setdelegate(b) -- in this case 'a' is the return value).
.. js:function:: table.getdelegate()
returns the table's delegate or null if no delegate was set.
.. js:function:: table.filter(func(key,val))
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.
.. js:function:: table.keys()
returns an array containing all the keys of the table slots.
.. js:function:: table.values()
returns an array containing all the values of the table slots.
^^^^^^
Array
^^^^^^
.. js:function:: array.len()
returns the length of the array
.. js:function:: array.append(val)
appends the value 'val' at the end of the array. Returns array itself.
.. js:function:: array.push(val)
appends the value 'val' at the end of the array. Returns array itself.
.. js:function:: array.extend(array)
Extends the array by appending all the items in the given array. Returns array itself.
.. js:function:: array.pop()
removes a value from the back of the array and returns it.
.. js:function:: array.top()
returns the value of the array with the higher index
.. js:function:: array.insert(idx,val)
inserts the value 'val' at the position 'idx' in the array. Returns array itself.
.. js:function:: array.remove(idx)
removes the value at the position 'idx' in the array and returns its value.
.. js:function:: 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.
.. js:function:: 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.
.. js:function:: array.reverse()
reverse the elements of the array in place. Returns array itself.
.. js:function:: 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.
.. js:function:: array.weakref()
returns a weak reference to the object.
.. js:function:: array.tostring()
returns the string "(array : pointer)".
.. js:function:: array.clear()
removes all the items from the array
.. js:function:: 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).
.. js:function:: 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.
.. js:function:: array.reduce(func(prevval,curval), [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.
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.
.. js:function:: array.filter(func(index,val))
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.
.. js:function:: array.find(value)
Performs a linear search for the value in the array. Returns the index of the value if it was found null otherwise.
^^^^^^^^
Function
^^^^^^^^
.. js:function:: function.call(_this,args...)
calls the function with the specified environment object('this') and parameters
.. js:function:: 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')
.. js:function:: 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.
.. js:function:: 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')
.. js:function:: function.weakref()
returns a weak reference to the object.
.. js:function:: function.tostring()
returns the string "(closure : pointer)".
.. js:function:: function.setroot(table)
sets the root table of a closure
.. js:function:: function.getroot()
returns the root table of the closure
.. js:function:: 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.
.. js:function:: function.getinfos()
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 squirrel function
{
native = false
name = "zefuncname"
src = "/somthing/something.nut"
parameters = ["a","b","c"]
defparams = [1,"def"]
varargs = 2
}
//native C function
{
native = true
name = "zefuncname"
paramscheck = 2
typecheck = [83886082,83886384] //this is the typemask (see C defines OT_INTEGER,OT_FLOAT etc...)
}
^^^^^
Class
^^^^^
.. js:function:: 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) ).
.. js:function:: class.getattributes(membername)
returns the attributes of the specified member. if the parameter member is null the function returns the class level attributes.
.. js:function:: class.setattributes(membername,attr)
sets the attribute of the specified member and returns the previous attribute value. if the parameter member is null the function sets the class level attributes.
.. js:function:: 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.
.. js:function:: class.weakref()
returns a weak reference to the object.
.. js:function:: class.tostring()
returns the string "(class : pointer)".
.. js:function:: class.rawget(key)
tries to get a value from the slot 'key' without employing delegation
.. js:function:: 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.
.. js:function:: class.newmember(key,val,[attrs],[bstatic])
sets/adds the slot 'key' with the value 'val' and attributes 'attrs' and if present invokes the _newmember metamethod. If bstatic is true the slot will be added as static. If the slot does not exists , it will be created.
.. js:function:: class.rawnewmember(key,val,[attrs],[bstatic])
sets/adds the slot 'key' with the value 'val' and attributes 'attrs'. If bstatic is true the slot will be added as static. If the slot does not exist, it will be created. It doesn't invoke any metamethod.
^^^^^^^^^^^^^^
Class Instance
^^^^^^^^^^^^^^
.. js:function:: instance.getclass()
returns the class that created the instance.
.. js:function:: instance.rawin(key)
:param 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.
.. js:function:: instance.weakref()
returns a weak reference to the object.
.. js:function:: instance.tostring()
tries to invoke the _tostring metamethod, if failed. returns "(instance : pointer)".
.. js:function:: instance.rawget(key)
tries to get a value from the slot 'key' without employing delegation
.. js:function:: 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.
^^^^^^^^^^^^^^
Generator
^^^^^^^^^^^^^^
.. js:function:: generator.getstatus()
returns the status of the generator as string : "running", "dead" or "suspended".
.. js:function:: generator.weakref()
returns a weak reference to the object.
.. js:function:: generator.tostring()
returns the string "(generator : pointer)".
^^^^^^^^^^^^^^
Thread
^^^^^^^^^^^^^^
.. js:function:: thread.call(...)
starts the thread with the specified parameters
.. js:function:: 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())
.. js:function:: thread.wakeupthrow(objtothrow,[propagateerror = true])
wakes up a suspended thread, throwing an exception in the awaken thread, throwing the object 'objtothrow'.
.. js:function:: thread.getstatus()
returns the status of the thread ("idle","running","suspended")
.. js:function:: thread.weakref()
returns a weak reference to the object.
.. js:function:: thread.tostring()
returns the string "(thread : pointer)".
.. js:function:: 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).
^^^^^^^^^^^^^^
Weak Reference
^^^^^^^^^^^^^^
.. js:function:: weakreference.ref()
returns the object that the weak reference is pointing at; null if the object that was point at was destroyed.
.. js:function:: weakreference.weakref()
returns a weak reference to the object.
.. js:function:: weakreference.tostring()
returns the string "(weakref : pointer)".

View File

@ -0,0 +1,429 @@
.. _classes:
=================
Classes
=================
.. index::
single: Classes
Squirrel implements a class mechanism similar to languages like Java/C++/etc...
however because of its dynamic nature it differs in several aspects.
Classes are first class objects like integer or strings and can be stored in
table slots local variables, arrays and passed as function parameters.
-----------------
Class Declaration
-----------------
.. index::
pair: declaration; Class
single: Class Declaration
A class object is created through the keyword 'class' . The class object follows
the same declaration syntax of a table(see :ref:`Tables <tables>`) with the only difference
of using ';' as optional separator rather than ','.
For instance: ::
class Foo {
//constructor
constructor(a)
{
testy = ["stuff",1,2,3,a];
}
//member function
function PrintTesty()
{
foreach(i,val in testy)
{
::print("idx = "+i+" = "+val+" \n");
}
}
//property
testy = null;
}
the previous code example is a syntactic sugar for: ::
Foo <- class {
//constructor
constructor(a)
{
testy = ["stuff",1,2,3,a];
}
//member function
function PrintTesty()
{
foreach(i,val in testy)
{
::print("idx = "+i+" = "+val+" \n");
}
}
//property
testy = null;
}
in order to emulate namespaces, it is also possible to declare something like this::
//just 2 regular nested tables
FakeNamespace <- {
Utils = {}
}
class FakeNamespace.Utils.SuperClass {
constructor()
{
::print("FakeNamespace.Utils.SuperClass")
}
function DoSomething()
{
::print("DoSomething()")
}
}
function FakeNamespace::Utils::SuperClass::DoSomethingElse()
{
::print("FakeNamespace::Utils::SuperClass::DoSomethingElse()")
}
local testy = FakeNamespace.Utils.SuperClass();
testy.DoSomething();
testy.DoSomethingElse();
After its declaration, methods or properties can be added or modified by following
the same rules that apply to a table(operator ``<-``).::
//adds a new property
Foo.stuff <- 10;
//modifies the default value of an existing property
Foo.testy <- "I'm a string";
//adds a new method
function Foo::DoSomething(a,b)
{
return a+b;
}
After a class is instantiated is no longer possible to add new properties however is possible to add or replace methods.
^^^^^^^^^^^^^^^^
Static variables
^^^^^^^^^^^^^^^^
.. index::
pair: static variables; Class
single: Static variables
Squirrel's classes support static member variables. A static variable shares its value
between all instances of the class. Statics are declared by prefixing the variable declaration
with the keyword ``static``; the declaration must be in the class body.
.. note:: Statics are read-only.
::
class Foo {
constructor()
{
//..stuff
}
name = "normal variable";
//static variable
static classname = "The class name is foo";
};
^^^^^^^^^^^^^^^^
Class Attributes
^^^^^^^^^^^^^^^^
.. index::
pair: attributes; Class
single: Class Attributes
Classes allow to associate attributes to it's members. Attributes are a form of metadata
that can be used to store application specific informations, like documentations
strings, properties for IDEs, code generators etc...
Class attributes are declared in the class body by preceding the member declaration and
are delimited by the symbol ``</`` and ``/>``.
Here an example: ::
class Foo </ test = "I'm a class level attribute" />{
</ test = "freakin attribute" /> //attributes of PrintTesty
function PrintTesty()
{
foreach(i,val in testy)
{
::print("idx = "+i+" = "+val+" \n");
}
}
</ flippy = 10 , second = [1,2,3] /> //attributes of testy
testy = null;
}
Attributes are, matter of fact, a table. Squirrel uses ``</ />`` syntax
instead of curly brackets ``{}`` for the attribute declaration to increase readability.
This means that all rules that apply to tables apply to attributes.
Attributes can be retrieved through the built-in function ``classobj.getattributes(membername)`` (see <link linkend="builtin">built-in functions</link>).
and can be modified/added through the built-in function ``classobj.setattributes(membername,val)``.
the following code iterates through the attributes of all Foo members.::
foreach(member,val in Foo)
{
::print(member+"\n");
local attr;
if((attr = Foo.getattributes(member)) != null) {
foreach(i,v in attr)
{
::print("\t"+i+" = "+(typeof v)+"\n");
}
}
else {
::print("\t<no attributes>\n")
}
}
-----------------
Class Instances
-----------------
.. index::
pair: instances; Class
single: Class Instances
The class objects inherits several of the table's feature with the difference that multiple instances of the
same class can be created.
A class instance is an object that share the same structure of the table that created it but
holds is own values.
Class *instantiation* uses function notation.
A class instance is created by calling a class object. Can be useful to imagine a class like a function
that returns a class instance.::
//creates a new instance of Foo
local inst = Foo();
When a class instance is created its member are initialized *with the same value* specified in the
class declaration. The values are copied verbatim, *no cloning is performed* even if the value is a container or a class instances.
.. note:: FOR C# and Java programmers:
Squirrel doesn't clone member's default values nor executes the member declaration for each instance(as C# or java).
So consider this example: ::
class Foo {
myarray = [1,2,3]
mytable = {}
}
local a = Foo();
local b = Foo();
In the snippet above both instances will refer to the same array and same table.To achieve what a C# or Java programmer would
expect, the following approach should be taken. ::
class Foo {
myarray = null
mytable = null
constructor()
{
myarray = [1,2,3]
mytable = {}
}
}
local a = Foo();
local b = Foo();
When a class defines a method called 'constructor', the class instantiation operation will
automatically invoke it for the newly created instance.
The constructor method can have parameters, this will impact on the number of parameters
that the *instantiation operation* will require.
Constructors, as normal functions, can have variable number of parameters (using the parameter ``...``).::
class Rect {
constructor(w,h)
{
width = w;
height = h;
}
x = 0;
y = 0;
width = null;
height = null;
}
//Rect's constructor has 2 parameters so the class has to be 'called'
//with 2 parameters
local rc = Rect(100,100);
After an instance is created, its properties can be set or fetched following the
same rules that apply to tables. Methods cannot be set.
Instance members cannot be removed.
The class object that created a certain instance can be retrieved through the built-in function
``instance.getclass()`` (see :ref:`built-in functions <builtin_functions>`)
The operator ``instanceof`` tests if a class instance is an instance of a certain class.::
local rc = Rect(100,100);
if(rc instanceof ::Rect) {
::print("It's a rect");
}
else {
::print("It isn't a rect");
}
.. note:: Since Squirrel 3.x instanceof doesn't throw an exception if the left expression is not a class, it simply fails
--------------
Inheritance
--------------
.. index::
pair: inheritance; Class
single: Inheritance
Squirrel's classes support single inheritance by adding the keyword ``extends``, followed
by an expression, in the class declaration.
The syntax for a derived class is the following: ::
class SuperFoo extends Foo {
function DoSomething() {
::print("I'm doing something");
}
}
When a derived class is declared, Squirrel first copies all base's members in the
new class then proceeds with evaluating the rest of the declaration.
A derived class inherit all members and properties of it's base, if the derived class
overrides a base function the base implementation is shadowed.
It's possible to access a overridden method of the base class by fetching the method from
through the 'base' keyword.
Here an example: ::
class Foo {
function DoSomething() {
::print("I'm the base");
}
};
class SuperFoo extends Foo {
//overridden method
function DoSomething() {
//calls the base method
base.DoSomething();
::print("I'm doing something");
}
}
Same rule apply to the constructor. The constructor is a regular function (apart from being automatically invoked on construction).::
class BaseClass {
constructor()
{
::print("Base constructor\n");
}
}
class ChildClass extends BaseClass {
constructor()
{
base.constructor();
::print("Child constructor\n");
}
}
local test = ChildClass();
The base class of a derived class can be retrieved through the built-in method ``getbase()``.::
local thebaseclass = SuperFoo.getbase();
Note that because methods do not have special protection policies when calling methods of the same
objects, a method of a base class that calls a method of the same class can end up calling a overridden method of the derived class.
A method of a base class can be explicitly invoked by a method of a derived class though the keyword ``base`` (as in base.MyMethod() ).::
class Foo {
function DoSomething() {
::print("I'm the base");
}
function DoIt()
{
DoSomething();
}
};
class SuperFoo extends Foo {
//overridden method
function DoSomething() {
::print("I'm the derived");
}
function DoIt() {
base.DoIt();
}
}
//creates a new instance of SuperFoo
local inst = SuperFoo();
//prints "I'm the derived"
inst.DoIt();
----------------------
Metamethods
----------------------
.. index::
pair: metamethods; Class
single: Class metamethods
Class instances allow the customization of certain aspects of the
their semantics through metamethods(see see :ref:`Metamethods <metamethods>`).
For C++ programmers: "metamethods behave roughly like overloaded operators".
The metamethods supported by classes are ``_add, _sub, _mul, _div, _unm, _modulo,
_set, _get, _typeof, _nexti, _cmp, _call, _delslot, _tostring``
Class objects instead support only 2 metamethods : ``_newmember`` and ``_inherited``
the following example show how to create a class that implements the metamethod ``_add``.::
class Vector3 {
constructor(...)
{
if(vargv.len() >= 3) {
x = vargv[0];
y = vargv[1];
z = vargv[2];
}
}
function _add(other)
{
return ::Vector3(x+other.x,y+other.y,z+other.z);
}
x = 0;
y = 0;
z = 0;
}
local v0 = Vector3(1,2,3)
local v1 = Vector3(11,12,13)
local v2 = v0 + v1;
::print(v2.x+","+v2.y+","+v2.z+"\n");
Since version 2.1, classes support 2 metamethods ``_inherited`` and ``_newmember``.
``_inherited`` is invoked when a class inherits from the one that implements ``_inherited``.
``_newmember`` is invoked for each member that is added to the class(at declaration time).

View File

@ -0,0 +1,97 @@
.. _constants_and_enumerations:
========================
Constants & Enumerations
========================
.. index::
single: Constants & Enumerations
Squirrel allows to bind constant values to an identifier that will be evaluated compile-time.
This is achieved though constants and Enumerations.
---------------
Constants
---------------
.. index::
single: Constants
Constants bind a specific value to an identifier. Constants are similar to
global values, except that they are evaluated compile time and their value cannot be changed.
constants values can only be integers, floats or string literals. No expression are allowed.
are declared with the following syntax.::
const foobar = 100;
const floatbar = 1.2;
const stringbar = "I'm a constant string";
constants are always globally scoped, from the moment they are declared, any following code
can reference them.
Constants will shadow any global slot with the same name( the global slot will remain visible by using the ``::`` syntax).::
local x = foobar * 2;
---------------
Enumerations
---------------
.. index::
single: Enumerations
As Constants, Enumerations bind a specific value to a name. Enumerations are also evaluated at compile time
and their value cannot be changed.
An enum declaration introduces a new enumeration into the program.
Enumeration values can only be integers, floats or string literals. No expression are allowed.::
enum Stuff {
first, //this will be 0
second, //this will be 1
third //this will be 2
}
or::
enum Stuff {
first = 10
second = "string"
third = 1.2
}
An enum value is accessed in a manner that's similar to accessing a static class member.
The name of the member must be qualified with the name of the enumeration, for example ``Stuff.second``
Enumerations will shadow any global slot with the same name( the global slot will remain visible by using the ``::`` syntax).::
local x = Stuff.first * 2;
--------------------
Implementation notes
--------------------
Enumerations and Constants are a compile-time feature. Only integers, string and floats can be declared as const/enum;
No expressions are allowed(because they would have to be evaluated compile time).
When a const or an enum is declared, it is added compile time to the ``consttable``. This table is stored in the VM shared state
and is shared by the VM and all its threads.
The ``consttable`` is a regular squirrel table; In the same way as the ``roottable``
it can be modified runtime.
You can access the ``consttable`` through the built-in function ``getconsttable()``
and also change it through the built-in function ``setconsttable()``
here some example: ::
//creates a constant
getconsttable()["something"] <- 10"
//creates an enumeration
getconsttable()["somethingelse"] <- { a = "10", c = "20", d = "200"};
//deletes the constant
delete getconsttable()["something"]
//deletes the enumeration
delete getconsttable()["somethingelse"]
This system allows to procedurally declare constants and enumerations, it is also possible to assign any squirrel type
to a constant/enumeration(function,classes etc...). However this will make serialization of a code chunk impossible.

View File

@ -0,0 +1,162 @@
.. _datatypes_and_values:
=====================
Values and Data types
=====================
While Squirrel is a dynamically typed language and variables do not
have a type, different operations may interpret the variable as
containing a type. Squirrel's basic types are integer, float, string,
null, table, array, function, generator, class, instance, bool, thread
and userdata.
.. _userdata-index:
--------
Integer
--------
An Integer represents a 32 bit (or better) signed number.::
local a = 123 //decimal
local b = 0x0012 //hexadecimal
local c = 075 //octal
local d = 'w' //char code
--------
Float
--------
A float represents a 32 bit (or better) floating point number.::
local a=1.0
local b=0.234
--------
String
--------
Strings are an immutable sequence of characters. In order to modify a
string is it necessary create a new one.
Squirrel's strings are similar to strings in C or C++. They are
delimited by quotation marks(``"``) and can contain escape
sequences (``\t``, ``\a``, ``\b``, ``\n``, ``\r``, ``\v``, ``\f``,
``\\``, ``\"``, ``\'``, ``\0``, ``\x<hh>``, ``\u<hhhh>`` and
``\U<hhhhhhhh>``).
Verbatim string literals do not interpret escape sequences. They begin
with ``@"`` and end with the matching quote. Verbatim string literals
also can extend over a line break. If they do, they include any white
space characters between the quotes: ::
local a = "I'm a wonderful string\n"
// has a newline at the end of the string
local x = @"I'm a verbatim string\n"
// the \n is literal, similar to "\\n" in a regular string.
However, a doubled quotation mark within a verbatim string is replaced
by a single quotation mark: ::
local multiline = @"
this is a multiline string
it will ""embed"" all the new line
characters
"
--------
Null
--------
The null value is a primitive value that represents the null, empty, or non-existent
reference. The type Null has exactly one value, called null.::
local a = null
--------
Bool
--------
Bool is a double-valued (Boolean) data type. Its literals are ``true``
and ``false``. A bool value expresses the validity of a condition
(tells whether the condition is true or false).::
local a = true;
--------
Table
--------
Tables are associative containers implemented as a set of key/value pairs
called slots.::
local t={}
local test=
{
a=10
b=function(a) { return a+1; }
}
--------
Array
--------
Arrays are simple sequence of objects. Their size is dynamic and their index always starts from 0.::
local a = ["I'm","an","array"]
local b = [null]
b[0] = a[2];
--------
Function
--------
Functions are similar to those in other C-like languages with a few key differences (see below).
--------
Class
--------
Classes are associative containers implemented as sets of key/value
pairs. Classes are created through a 'class expression' or a 'class
statement'. class members can be inherited from another class object
at creation time. After creation, members can be added until an
instance of the class is created.
--------------
Class Instance
--------------
Class instances are created by calling a *class object*. Instances, as
tables, are implemented as sets of key/value pairs. Instance members
cannot be dynamically added or removed; however the value of the
members can be changed.
---------
Generator
---------
Generators are functions that can be suspended with the statement
'yield' and resumed later (see :ref:`Generators <generators>`).
---------
Userdata
---------
Userdata objects are blobs of memory or pointers defined by the host
application but stored within Squirrel variables (See :ref:`Userdata
and UserPointers <embedding_userdata_and_userpointers>`).
---------
Thread
---------
Threads are objects representing a cooperative thread of execution,
also known as coroutines.
--------------
Weak Reference
--------------
Weak References are objects that point to another (non-scalar) object but do not own a strong reference to it.
(See :ref:`Weak References <weak_references>`).

View File

@ -0,0 +1,35 @@
.. _delegation:
========================
Delegation
========================
.. index::
single: Delegation
Squirrel supports implicit delegation. Every table or userdata can have a parent table
(delegate). A parent table is a normal table that allows the definition of special behaviors
for his child.
When a table (or userdata) is indexed with a key that doesn't correspond to one of its
slots, the interpreter automatically delegates the get (or set) operation to its parent.::
Entity <- {
}
function Entity::DoStuff()
{
::print(_name);
}
local newentity = {
_name="I'm the new entity"
}
newentity.setdelegate(Entity)
newentity.DoStuff(); //prints "I'm the new entity"
The delegate of a table can be retreived through built-in method ``table.getdelegate()``.::
local thedelegate = newentity.getdelegate();

View File

@ -0,0 +1,95 @@
.. _executioncontext:
=======================
Execution Context
=======================
.. index::
single: execution context
The execution context is the union of the function stack frame and the function
environment object(this) and the function root(root table).
The stack frame is the portion of stack where the local variables declared in its body are
stored.
The environment object is an implicit parameter that is automatically passed by the
function caller (see see :ref:`functions <functions>`).
The root table is a table associated to the function during its creation.
The root table value of a function is the root table of the VM at the function creation.
The root table of function can also be changed after creation with closure.setroot().
During the execution, the body of a function can only transparently refer to his execution
context.
This mean that a single identifier can refer to a local variable, to an environment object slot
or to the slot of the closure root table;
The environment object can be explicitly accessed by the keyword ``this``.
The closure root table can be explicitly accessed through the operator ``::`` (see :ref:`Variables <variables>`).
.. _variables:
-----------------
Variables
-----------------
There are two types of variables in Squirrel, local variables and tables/arrays slots.
Because global variables(variables stored in the root of a closure) are stored in a table, they are table slots.
A single identifier refers to a local variable or a slot in the environment object.::
derefexp := id;
::
_table["foo"]
_array[10]
with tables we can also use the '.' syntax::
derefexp := exp '.' id
::
_table.foo
Squirrel first checks if an identifier is a local variable (function arguments are local
variables) if not looks up the environment object (this) and finally looks up
to the closure root.
For instance:::
function testy(arg)
{
local a=10;
print(a);
return arg;
}
in this case 'foo' will be equivalent to 'this.foo' or this["foo"].
Global variables are stored in a table called the root table. Usually in the global scope the
environment object is the root table, but to explicitly access the closure root of the function from
another scope, the slot name must be prefixed with ``'::'`` (``::foo``).
For instance:::
function testy(arg)
{
local a=10;
return arg+::foo;
}
accesses the variable 'foo' in the closure root table.
Since Squirrel 3.1 each function has a weak reference to a specific root table, this can differ from the current VM root table.::
function test() {
foo = 10;
}
is equivalent to write::
function test() {
if("foo" in this) {
this.foo = 10;
}else {
::foo = 10;
}
}

View File

@ -0,0 +1,374 @@
.. _expressions:
=================
Expressions
=================
.. index::
single: Expressions
----------------
Assignment
----------------
.. index::
single: assignment(=)
single: new slot(<-)
::
exp := derefexp '=' exp
exp:= derefexp '<-' exp
squirrel implements 2 kind of assignment: the normal assignment(=)::
a = 10;
and the "new slot" assignment.::
a <- 10;
The new slot expression allows to add a new slot into a table(see :ref:`Tables <tables>`). If the slot
already exists in the table it behaves like a normal assignment.
----------------
Operators
----------------
.. index::
single: Operators
^^^^^^^^^^^^^
?: Operator
^^^^^^^^^^^^^
.. index::
pair: ?: Operator; Operators
::
exp := exp_cond '?' exp1 ':' exp2
conditionally evaluate an expression depending on the result of an expression.
^^^^^^^^^^^^^
Arithmetic
^^^^^^^^^^^^^
.. index::
pair: Arithmetic Operators; Operators
::
exp:= 'exp' op 'exp'
Squirrel supports the standard arithmetic operators ``+, -, *, / and %``.
Other than that is also supports compact operators (``+=,-=,*=,/=,%=``) and
increment and decrement operators(++ and --);::
a += 2;
//is the same as writing
a = a + 2;
x++
//is the same as writing
x = x + 1
All operators work normally with integers and floats; if one operand is an integer and one
is a float the result of the expression will be float.
The + operator has a special behavior with strings; if one of the operands is a string the
operator + will try to convert the other operand to string as well and concatenate both
together. For instances and tables, ``_tostring`` is invoked.
^^^^^^^^^^^^^
Relational
^^^^^^^^^^^^^
.. index::
pair: Relational Operators; Operators
::
exp:= 'exp' op 'exp'
Relational operators in Squirrel are : ``==, <, <=, <, <=, !=``
These operators return true if the expression is false and a value different than true if the
expression is true. Internally the VM uses the integer 1 as true but this could change in
the future.
^^^^^^^^^^^^^^
3 ways compare
^^^^^^^^^^^^^^
.. index::
pair: 3 ways compare operator; Operators
::
exp:= 'exp' <=> 'exp'
the 3 ways compare operator <=> compares 2 values A and B and returns an integer less than 0
if A < B, 0 if A == B and an integer greater than 0 if A > B.
^^^^^^^^^^^^^^
Logical
^^^^^^^^^^^^^^
.. index::
pair: Logical operators; Operators
::
exp := exp op exp
exp := '!' exp
Logical operators in Squirrel are : ``&&, ||, !``
The operator ``&&`` (logical and) returns null if its first argument is null, otherwise returns
its second argument.
The operator ``||`` (logical or) returns its first argument if is different than null, otherwise
returns the second argument.
The '!' operator will return null if the given value to negate was different than null, or a
value different than null if the given value was null.
^^^^^^^^^^^^^^^
in operator
^^^^^^^^^^^^^^^
.. index::
pair: in operator; Operators
::
exp:= keyexp 'in' tableexp
Tests the existence of a slot in a table.
Returns true if *keyexp* is a valid key in *tableexp* ::
local t=
{
foo="I'm foo",
[123]="I'm not foo"
}
if("foo" in t) dostuff("yep");
if(123 in t) dostuff();
^^^^^^^^^^^^^^^^^^^
instanceof operator
^^^^^^^^^^^^^^^^^^^
.. index::
pair: instanceof operator; Operators
::
exp:= instanceexp 'instanceof' classexp
Tests if a class instance is an instance of a certain class.
Returns true if *instanceexp* is an instance of *classexp*.
^^^^^^^^^^^^^^^^^^^
typeof operator
^^^^^^^^^^^^^^^^^^^
.. index::
pair: typeof operator; Operators
::
exp:= 'typeof' exp
returns the type name of a value as string.::
local a={},b="squirrel"
print(typeof a); //will print "table"
print(typeof b); //will print "string"
^^^^^^^^^^^^^^^^^^^
Comma operator
^^^^^^^^^^^^^^^^^^^
.. index::
pair: Comma operator; Operators
::
exp:= exp ',' exp
The comma operator evaluates two expression left to right, the result of the operator is
the result of the expression on the right; the result of the left expression is discarded.::
local j=0,k=0;
for(local i=0; i<10; i++ , j++)
{
k = i + j;
}
local a,k;
a = (k=1,k+2); //a becomes 3
^^^^^^^^^^^^^^^^^^^
Bitwise Operators
^^^^^^^^^^^^^^^^^^^
.. index::
pair: Bitwise Operators; Operators
::
exp:= 'exp' op 'exp'
exp := '~' exp
Squirrel supports the standard C-like bitwise operators ``&, |, ^, ~, <<, >>`` plus the unsigned
right shift operator ``>>>``. The unsigned right shift works exactly like the normal right shift operator(``>>``)
except for treating the left operand as an unsigned integer, so is not affected by the sign. Those operators
only work on integer values; passing of any other operand type to these operators will
cause an exception.
^^^^^^^^^^^^^^^^^^^^^
Operators precedence
^^^^^^^^^^^^^^^^^^^^^
.. index::
pair: Operators precedence; Operators
+---------------------------------------+-----------+
| ``-, ~, !, typeof , ++, --`` | highest |
+---------------------------------------+-----------+
| ``/, *, %`` | ... |
+---------------------------------------+-----------+
| ``+, -`` | |
+---------------------------------------+-----------+
| ``<<, >>, >>>`` | |
+---------------------------------------+-----------+
| ``<, <=, >, >=, instanceof`` | |
+---------------------------------------+-----------+
| ``==, !=, <=>`` | |
+---------------------------------------+-----------+
| ``&`` | |
+---------------------------------------+-----------+
| ``^`` | |
+---------------------------------------+-----------+
| ``&&, in`` | |
+---------------------------------------+-----------+
| ``+=, =, -=, /=, *=, %=`` | ... |
+---------------------------------------+-----------+
| ``, (comma operator)`` | lowest |
+---------------------------------------+-----------+
.. _table_contructor:
-----------------
Table Constructor
-----------------
.. index::
single: Table Contructor
::
tslots := ( 'id' '=' exp | '[' exp ']' '=' exp ) [',']
exp := '{' [tslots] '}'
Creates a new table.::
local a = {} //create an empty table
A table constructor can also contain slots declaration; With the syntax: ::
local a = {
slot1 = "I'm the slot value"
}
An alternative syntax can be::
'[' exp1 ']' = exp2 [',']
A new slot with exp1 as key and exp2 as value is created::
local a=
{
[1]="I'm the value"
}
Both syntaxes can be mixed::
local table=
{
a=10,
b="string",
[10]={},
function bau(a,b)
{
return a+b;
}
}
The comma between slots is optional.
^^^^^^^^^^^^^^^^^^^^^^
Table with JSON syntax
^^^^^^^^^^^^^^^^^^^^^^
.. index::
single: Table with JSON syntax
Since Squirrel 3.0 is possible to declare a table using JSON syntax(see http://www.wikipedia.org/wiki/JSON).
the following JSON snippet: ::
local x = {
"id": 1,
"name": "Foo",
"price": 123,
"tags": ["Bar","Eek"]
}
is equivalent to the following squirrel code: ::
local x = {
id = 1,
name = "Foo",
price = 123,
tags = ["Bar","Eek"]
}
-----------------
clone
-----------------
.. index::
single: clone
::
exp:= 'clone' exp
Clone performs shallow copy of a table, array or class instance (copies all slots in the new object without
recursion). If the source table has a delegate, the same delegate will be assigned as
delegate (not copied) to the new table (see :ref:`Delegation <delegation>`).
After the new object is ready the "_cloned" meta method is called (see :ref:`Metamethods <metamethods>`).
When a class instance is cloned the constructor is not invoked(initializations must rely on ```_cloned``` instead
-----------------
Array contructor
-----------------
.. index::
single: Array constructor
::
exp := '[' [explist] ']'
Creates a new array.::
a <- [] //creates an empty array
Arrays can be initialized with values during the construction::
a <- [1,"string!",[],{}] //creates an array with 4 elements

View File

@ -0,0 +1,272 @@
.. _functions:
=================
Functions
=================
.. index::
single: Functions
Functions are first class values like integer or strings and can be stored in table slots,
local variables, arrays and passed as function parameters.
Functions can be implemented in Squirrel or in a native language with calling conventions
compatible with ANSI C.
--------------------
Function declaration
--------------------
.. index::
single: Function Declaration
Functions are declared through the function expression::
local a = function(a, b, c) { return a + b - c; }
or with the syntactic sugar::
function ciao(a,b,c)
{
return a+b-c;
}
that is equivalent to::
this.ciao <- function(a,b,c)
{
return a+b-c;
}
a local function can be declared with this syntactic sugar::
local function tuna(a,b,c)
{
return a+b-c;
}
that is equivalent to::
local tuna = function(a,b,c)
{
return a+b-c;
}
is also possible to declare something like::
T <- {}
function T::ciao(a,b,c)
{
return a+b-c;
}
//that is equivalent to write
T.ciao <- function(a,b,c)
{
return a+b-c;
}
//or
T <- {
function ciao(a,b,c)
{
return a+b-c;
}
}
^^^^^^^^^^^^^^^^^^
Default Paramaters
^^^^^^^^^^^^^^^^^^
.. index::
single: Function Default Paramaters
Squirrel's functions can have default parameters.
A function with default parameters is declared as follows: ::
function test(a,b,c = 10, d = 20)
{
....
}
when the function *test* is invoked and the parameter c or d are not specified,
the VM autometically assigns the default value to the unspecified parameter. A default parameter can be
any valid squirrel expression. The expression is evaluated at runtime.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function with variable number of paramaters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. index::
single: Function with variable number of paramaters
Squirrel's functions can have variable number of parameters(varargs functions).
A vararg function is declared by adding three dots (`...`) at the end of its parameter list.
When the function is called all the extra parameters will be accessible through the *array*
called ``vargv``, that is passed as implicit parameter.
``vargv`` is a regular squirrel array and can be used accordingly.::
function test(a,b,...)
{
for(local i = 0; i< vargv.len(); i++)
{
::print("varparam "+i+" = "+vargv[i]+"\n");
}
foreach(i,val in vargv)
{
::print("varparam "+i+" = "+val+"\n");
}
}
test("goes in a","goes in b",0,1,2,3,4,5,6,7,8);
---------------
Function calls
---------------
.. index::
single: Function calls
::
exp:= derefexp '(' explist ')'
The expression is evaluated in this order: derefexp after the explist (arguments) and at
the end the call.
A function call in Squirrel passes the current environment object *this* as a hidden parameter.
But when the function was immediately indexed from an object, *this* shall be the object
which was indexed, instead.
If we call a function with the syntax::
mytable.foo(x,y)
the environment object passed to 'foo' as *this* will be 'mytable' (since 'foo' was immediately indexed from 'mytable')
Whereas with the syntax::
foo(x,y) // implicitly equivalent to this.foo(x,y)
the environment object will be the current *this* (that is, propagated from the caller's *this*).
It may help to remember the rules in the following way:
foo(x,y) ---> this.foo(x,y)
table.foo(x,y) ---> call foo with (table,x,y)
It may also help to consider why it works this way: it's designed to assist with object-oriented style.
When calling 'foo(x,y)' it's assumed you're calling another member of the object (or of the file) and
so should operate on the same object.
When calling 'mytable.foo(x,y)' it's written plainly that you're calling a member of a different object.
---------------------------------------------
Binding an environment to a function
---------------------------------------------
.. index::
single: Binding an environment to a function
while by default a squirrel function call passes as environment object 'this', the object
where the function was indexed from. However, is also possible to statically bind an evironment to a
closure using the built-in method ``closure.bindenv(env_obj)``.
The method bindenv() returns a new instance of a closure with the environment bound to it.
When an environment object is bound to a function, every time the function is invoked, its
'this' parameter will always be the previously bound environent.
This mechanism is useful to implement callbacks systems similar to C# delegates.
.. note:: The closure keeps a weak reference to the bound environmet object, because of this if
the object is deleted, the next call to the closure will result in a ``null``
environment object.
---------------------------------------------
Lambda Expressions
---------------------------------------------
.. index::
single: Lambda Expressions
::
exp := '@' '(' paramlist ')' exp
Lambda expressions are a syntactic sugar to quickly define a function that consists of a single expression.
This feature comes handy when functional programming patterns are applied, like map/reduce or passing a compare method to
array.sort().
here a lambda expression::
local myexp = @(a,b) a + b
that is equivalent to::
local myexp = function(a,b) { return a + b; }
a more useful usage could be::
local arr = [2,3,5,8,3,5,1,2,6];
arr.sort(@(a,b) a <=> b);
arr.sort(@(a,b) -(a <=> b));
that could have been written as::
local arr = [2,3,5,8,3,5,1,2,6];
arr.sort(function(a,b) { return a <=> b; } );
arr.sort(function(a,b) { return -(a <=> b); } );
other than being limited to a single expression lambdas support all features of regular functions.
in fact are implemented as a compile time feature.
---------------------------------------------
Free Variables
---------------------------------------------
.. index::
single: Free Variables
A free variable is a variable external from the function scope as is not a local variable
or parameter of the function.
Free variables reference a local variable from a outer scope.
In the following example the variables 'testy', 'x' and 'y' are bound to the function 'foo'.::
local x=10,y=20
local testy="I'm testy"
function foo(a,b)
{
::print(testy);
return a+b+x+y;
}
A program can read or write a free variable.
---------------------------------------------
Tail Recursion
---------------------------------------------
.. index::
single: Tail Recursion
Tail recursion is a method for partially transforming a recursion in a program into an
iteration: it applies when the recursive calls in a function are the last executed
statements in that function (just before the return).
If this happenes the squirrel interpreter collapses the caller stack frame before the
recursive call; because of that very deep recursions are possible without risk of a stack
overflow.::
function loopy(n)
{
if(n>0){
::print("n="+n+"\n");
return loopy(n-1);
}
}
loopy(1000);

View File

@ -0,0 +1,51 @@
.. _generators:
=================
Generators
=================
.. index::
single: Generators
A function that contains a ``yield`` statement is called *'generator function'* .
When a generator function is called, it does not execute the function body, instead it
returns a new suspended generator.
The returned generator can be resumed through the resume statement while it is alive.
The yield keyword, suspends the execution of a generator and optionally returns the
result of an expression to the function that resumed the generator.
The generator dies when it returns, this can happen through an explicit return
statement or by exiting the function body; If an unhandled exception (or runtime error)
occurs while a generator is running, the generator will automatically die. A dead
generator cannot be resumed anymore.::
function geny(n)
{
for(local i=1;i<=n;i+=1)
yield i;
return null;
}
local gtor=geny(10);
local x;
while(x=resume gtor) print(x+"\n");
the output of this program will be::
1
2
3
4
5
6
7
8
9
10
generators can also be iterated using the foreach statement. When a generator is evaluated
by ``foreach``, the generator will be resumed for each iteration until it returns. The value
returned by the ``return`` statement will be ignored.
.. note:: A suspended generator will hold a strong reference to all the values stored in it's local variables except the ``this``
object that is only a weak reference. A running generator hold a strong reference also to the ``this`` object.

View File

@ -0,0 +1,154 @@
.. _lexical_structure:
=================
Lexical Structure
=================
.. index:: single: lexical structure
-----------
Identifiers
-----------
.. index:: single: identifiers
Identifiers start with an alphabetic character or the symbol '_' followed by any number
of alphabetic characters, '_' or digits ([0-9]). Squirrel is a case sensitive language
meaning that the lowercase and uppercase representation of the same alphabetic
character are considered different characters. For instance, "foo", "Foo" and "fOo" are
treated as 3 distinct identifiers.
-----------
Keywords
-----------
.. index:: single: keywords
The following words are reserved and cannot be used as identifiers:
+------------+------------+-----------+------------+------------+-------------+
| base | break | case | catch | class | clone |
+------------+------------+-----------+------------+------------+-------------+
| continue | const | default | delete | else | enum |
+------------+------------+-----------+------------+------------+-------------+
| extends | for | foreach | function | if | in |
+------------+------------+-----------+------------+------------+-------------+
| local | null | resume | return | switch | this |
+------------+------------+-----------+------------+------------+-------------+
| throw | try | typeof | while | yield | constructor |
+------------+------------+-----------+------------+------------+-------------+
| instanceof | true | false | static | __LINE__ | __FILE__ |
+------------+------------+-----------+------------+------------+-------------+
Keywords are covered in detail later in this document.
-----------
Operators
-----------
.. index:: single: operators
Squirrel recognizes the following operators:
+----------+----------+----------+----------+----------+----------+----------+----------+
| ``!`` | ``!=`` | ``||`` | ``==`` | ``&&`` | ``>=`` | ``<=`` | ``>`` |
+----------+----------+----------+----------+----------+----------+----------+----------+
| ``<=>`` | ``+`` | ``+=`` | ``-`` | ``-=`` | ``/`` | ``/=`` | ``*`` |
+----------+----------+----------+----------+----------+----------+----------+----------+
| ``*=`` | ``%`` | ``%=`` | ``++`` | ``--`` | ``<-`` | ``=`` | ``&`` |
+----------+----------+----------+----------+----------+----------+----------+----------+
| ``^`` | ``|`` | ``~`` | ``>>`` | ``<<`` | ``>>>`` | | |
+----------+----------+----------+----------+----------+----------+----------+----------+
------------
Other tokens
------------
.. index::
single: delimiters
single: other tokens
Other significant tokens are:
+----------+----------+----------+----------+----------+----------+
| ``{`` | ``}`` | ``[`` | ``]`` | ``.`` | ``:`` |
+----------+----------+----------+----------+----------+----------+
| ``::`` | ``'`` | ``;`` | ``"`` | ``@"`` | |
+----------+----------+----------+----------+----------+----------+
-----------
Literals
-----------
.. index::
single: literals
single: string literals
single: numeric literals
Squirrel accepts integer numbers, floating point numbers and string literals.
+-------------------------------+------------------------------------------+
| ``34`` | Integer number(base 10) |
+-------------------------------+------------------------------------------+
| ``0xFF00A120`` | Integer number(base 16) |
+-------------------------------+------------------------------------------+
| ``0753`` | Integer number(base 8) |
+-------------------------------+------------------------------------------+
| ``'a'`` | Integer number |
+-------------------------------+------------------------------------------+
| ``1.52`` | Floating point number |
+-------------------------------+------------------------------------------+
| ``1.e2`` | Floating point number |
+-------------------------------+------------------------------------------+
| ``1.e-2`` | Floating point number |
+-------------------------------+------------------------------------------+
| ``"I'm a string"`` | String |
+-------------------------------+------------------------------------------+
| ``@"I'm a verbatim string"`` | String |
+-------------------------------+------------------------------------------+
| ``@" I'm a`` | |
| ``multiline verbatim string`` | |
| ``"`` | String |
+-------------------------------+------------------------------------------+
Pesudo BNF
.. productionlist::
IntegerLiteral : [1-9][0-9]* | '0x' [0-9A-Fa-f]+ | ''' [.]+ ''' | 0[0-7]+
FloatLiteral : [0-9]+ '.' [0-9]+
FloatLiteral : [0-9]+ '.' 'e'|'E' '+'|'-' [0-9]+
StringLiteral: '"'[.]* '"'
VerbatimStringLiteral: '@''"'[.]* '"'
-----------
Comments
-----------
.. index:: single: comments
A comment is text that the compiler ignores but that is useful for programmers.
Comments are normally used to embed annotations in the code. The compiler
treats them as white space.
A comment can be ``/*`` (slash, asterisk) characters, followed by any
sequence of characters (including new lines),
followed by the ``*/`` characters. This syntax is the same as ANSI C.::
/*
this is
a multiline comment.
this lines will be ignored by the compiler
*/
A comment can also be ``//`` (two slashes) characters, followed by any sequence of
characters. A new line not immediately preceded by a backslash terminates this form of
comment. It is commonly called a *"single-line comment."*::
//this is a single line comment. this line will be ignored by the compiler
The character ``#`` is an alternative syntax for single line comment.::
# this is also a single line comment.
This to facilitate the use of squirrel in UNIX-style shell scripts.

View File

@ -0,0 +1,270 @@
.. _metamethods:
-----------
Metamethods
-----------
Metamethods are a mechanism that allows the customization of certain aspects of the
language semantics. Those methods are normal functions placed in a table
parent(delegate) or class declaration; It is possible to change many aspects of a table/class instance behavior by just defining
a metamethod. Class objects (not instances) support only 2 metamethods ``_newmember, _inherited`` .
For example when we use relational operators other than '==' on 2 tables, the VM will
check if the table has a method in his parent called '_cmp'; if so it will call it to determine
the relation between the tables.::
local comparable={
_cmp = function (other)
{
if(name<other.name)return -1;
if(name>other.name)return 1;
return 0;
}
}
local a={ name="Alberto" }.setdelegate(comparable);
local b={ name="Wouter" }.setdelegate(comparable);
if(a>b)
print("a>b")
else
print("b<=a");
for classes the previous code become: ::
class Comparable {
constructor(n)
{
name = n;
}
function _cmp(other)
{
if(name<other.name) return -1;
if(name>other.name) return 1;
return 0;
}
name = null;
}
local a = Comparable("Alberto");
local b = Comparable("Wouter");
if(a>b)
print("a>b")
else
print("b<=a");
^^^^^
_set
^^^^^
::
_set(idx,val)
invoked when the index idx is not present in the object or in its delegate chain.
``_set`` must 'throw null' to notify that a key wasn't found but the there were not runtime errors (clean failure).
This allows the program to differentiate between a runtime error and a 'index not found'.
^^^^^
_get
^^^^^
::
_get(idx)
invoked when the index idx is not present in the object or in its delegate chain.
_get must 'throw null' to notify that a key wasn't found but the there were not runtime errors (clean failure).
This allows the program to differentiate between a runtime error and a 'index not found'.
^^^^^^^^^
_newslot
^^^^^^^^^
::
_newslot(key,value)
invoked when a script tries to add a new slot in a table.
if the slot already exists in the target table the method will not be invoked also if the
"new slot" operator is used.
^^^^^^^^^
_delslot
^^^^^^^^^
::
_delslot(key)
invoked when a script deletes a slot from a table.
if the method is invoked squirrel will not try to delete the slot himself
^^^^^^^^
_add
^^^^^^^^
::
_add(other)
the + operator
returns this + other
^^^^^^^^^^^^^^^^^^^^^^^^
_sub
^^^^^^^^^^^^^^^^^^^^^^^^
::
_sub(other)
the - operator (like _add)
^^^^^^^^^^^^^^^^^^^^^^^^
_mul
^^^^^^^^^^^^^^^^^^^^^^^^
::
_mul(other)
the ``*`` operator (like _add)
^^^^^^^^^^^^^^^^^^^^^^^^
_div
^^^^^^^^^^^^^^^^^^^^^^^^
::
_div(other)
the ``/`` operator (like _add)
^^^^^^^^^^^^^^^^^^^^^^^^
_modulo
^^^^^^^^^^^^^^^^^^^^^^^^
::
_modulo(other)
the ``%`` operator (like _add)
^^^^^^^^^
_unm
^^^^^^^^^
::
_unm()
the unary minus operator
^^^^^^^^^^^^^^^^^^^^^^^^
_typeof
^^^^^^^^^^^^^^^^^^^^^^^^
::
_typeof()
invoked by the typeof operator on tables, userdata, and class instances.
Returns the type of ``this`` as string
^^^^^^^^^^^^^^^^^^^^^^^^
_cmp
^^^^^^^^^^^^^^^^^^^^^^^^
::
_cmp(other)
invoked to emulate the ``< > <= >=`` and ``<=>`` operators
returns an integer as follow:
+-----------+----------------------------+
| returns | relationship |
+===========+============================+
| > 0 | if ``this`` > ``other`` |
+-----------+----------------------------+
| 0 | if ``this`` == ``other`` |
+-----------+----------------------------+
| < 0 | if ``this`` < ``other`` |
+-----------+----------------------------+
^^^^^^^^^^^^^^^^^^^^^^^^
_call
^^^^^^^^^^^^^^^^^^^^^^^^
::
_call(other)
invoked when a table, userdata, or class instance is called
^^^^^^^^^^^^^^^^^^^^^^^^
_cloned
^^^^^^^^^^^^^^^^^^^^^^^^
::
_cloned(original)
invoked when a table or class instance is cloned(in the cloned table)
^^^^^^^^^^^^^^^^^^^^^^^^
_nexti
^^^^^^^^^^^^^^^^^^^^^^^^
::
_nexti(previdx)
invoked when a userdata or class instance is iterated by a foreach loop.
If previdx==null it means that it is the first iteration.
The function has to return the index of the 'next' value.
^^^^^^^^^^^^^^^^^^^^^^^^
_tostring
^^^^^^^^^^^^^^^^^^^^^^^^
::
_tostring()
Invoked when during string concatenation or when the ``print`` function prints a table, instance, or userdata.
The method is also invoked by the sq_tostring() API.
Must return a string representation of the object.
^^^^^^^^^^^^^^^^^^^^^^^^
_inherited
^^^^^^^^^^^^^^^^^^^^^^^^
::
_inherited(attributes)
invoked when a class object inherits from the class implementing ``_inherited``.
The ``this`` contains the new class.
Return value is ignored.
^^^^^^^^^^^^^^^^^^^^^^^^
_newmember
^^^^^^^^^^^^^^^^^^^^^^^^
::
_newmember(index,value,attributes,isstatic)
invoked for each member declared in a class body (at declaration time).
If the function is implemented, members will not be added to the class.

View File

@ -0,0 +1,386 @@
.. _statements:
=================
Statements
=================
.. index::
single: statements
A squirrel program is a simple sequence of statements.::
stats := stat [';'|'\n'] stats
Statements in squirrel are comparable to the C-Family languages (C/C++, Java, C#
etc...): assignment, function calls, program flow control structures etc.. plus some
custom statement like yield, table and array constructors (All those will be covered in detail
later in this document).
Statements can be separated with a new line or ';' (or with the keywords case or default if
inside a switch/case statement), both symbols are not required if the statement is
followed by '}'.
------
Block
------
.. index::
pair: block; statement
::
stat := '{' stats '}'
A sequence of statements delimited by curly brackets ({ }) is called block;
a block is a statement itself.
-----------------------
Control Flow Statements
-----------------------
.. index::
single: control flow statements
squirrel implements the most common control flow statements: ``if, while, do-while, switch-case, for, foreach``
^^^^^^^^^^^^^^
true and false
^^^^^^^^^^^^^^
.. index::
single: true and false
single: true
single: false
Squirrel has a boolean type (bool) however like C++ it considers null, 0(integer) and 0.0(float)
as *false*, any other value is considered *true*.
^^^^^^^^^^^^^^^^^
if/else statement
^^^^^^^^^^^^^^^^^
.. index::
pair: if/else; statement
pair: if; statement
pair: else; statement
::
stat:= 'if' '(' exp ')' stat ['else' stat]
Conditionally execute a statement depending on the result of an expression.::
if(a>b)
a=b;
else
b=a;
////
if(a==10)
{
b=a+b;
return a;
}
^^^^^^^^^^^^^^^^^
while statement
^^^^^^^^^^^^^^^^^
.. index::
pair: while; statement
::
stat:= 'while' '(' exp ')' stat
Executes a statement while the condition is true.::
function testy(n)
{
local a=0;
while(a<n) a+=1;
while(1)
{
if(a<0) break;
a-=1;
}
}
^^^^^^^^^^^^^^^^^^
do/while statement
^^^^^^^^^^^^^^^^^^
.. index::
pair: do/while; statement
::
stat:= 'do' stat 'while' '(' expression ')'
Executes a statement once, and then repeats execution of the statement until a condition
expression evaluates to false.::
local a=0;
do
{
print(a+"\n");
a+=1;
} while(a>100)
^^^^^^^^^^^^^^^^^
switch statement
^^^^^^^^^^^^^^^^^
.. index::
pair: switch; statement
::
stat := 'switch' ''( exp ')' '{'
'case' case_exp ':'
stats
['default' ':'
stats]
'}'
Switch is a control statement allows multiple selections of code by passing control to one of the
case statements within its body.
The control is transferred to the case label whose case_exp matches with exp if none of
the case match will jump to the default label (if present).
A switch statement can contain any number if case instances, if 2 case have the same
expression result the first one will be taken in account first. The default label is only
allowed once and must be the last one.
A break statement will jump outside the switch block.
-----
Loops
-----
.. index::
single: Loops
^^^^^^^^
for
^^^^^^^^
.. index::
pair: for; statement
::
stat:= 'for' '(' [initexp] ';' [condexp] ';' [incexp] ')' statement
Executes a statement as long as a condition is different than false.::
for(local a=0;a<10;a+=1)
print(a+"\n");
//or
glob <- null
for(glob=0;glob<10;glob+=1){
print(glob+"\n");
}
//or
for(;;){
print(loops forever+"\n");
}
^^^^^^^^
foreach
^^^^^^^^
.. index::
pair: foreach; statement
::
'foreach' '(' [index_id','] value_id 'in' exp ')' stat
Executes a statement for every element contained in an array, table, class, string or generator.
If exp is a generator it will be resumed every iteration as long as it is alive; the value will
be the result of 'resume' and the index the sequence number of the iteration starting
from 0.::
local a=[10,23,33,41,589,56]
foreach(idx,val in a)
print("index="+idx+" value="+val+"\n");
//or
foreach(val in a)
print("value="+val+"\n");
-------
break
-------
.. index::
pair: break; statement
::
stat := 'break'
The break statement terminates the execution of a loop (for, foreach, while or do/while)
or jumps out of switch statement;
---------
continue
---------
.. index::
pair: continue; statement
::
stat := 'continue'
The continue operator jumps to the next iteration of the loop skipping the execution of
the following statements.
---------
return
---------
.. index::
pair: return; statement
::
stat:= return [exp]
The return statement terminates the execution of the current function/generator and
optionally returns the result of an expression. If the expression is omitted the function
will return null. If the return statement is used inside a generator, the generator will not
be resumable anymore.
---------
yield
---------
.. index::
pair: yield; statement
::
stat := yield [exp]
(see :ref:`Generators <generators>`).
---------------------------
Local variables declaration
---------------------------
.. index::
pair: Local variables declaration; statement
::
initz := id [= exp][',' initz]
stat := 'local' initz
Local variables can be declared at any point in the program; they exist between their
declaration to the end of the block where they have been declared.
*EXCEPTION:* a local declaration statement is allowed as first expression in a for loop.::
for(local a=0;a<10;a+=1)
print(a);
--------------------
Function declaration
--------------------
.. index::
pair: Function declaration; statement
::
funcname := id ['::' id]
stat:= 'function' id ['::' id]+ '(' args ')' stat
creates a new function.
-----------------
Class declaration
-----------------
.. index::
pair: Class declaration; statement
::
memberdecl := id '=' exp [';'] | '[' exp ']' '=' exp [';'] | functionstat | 'constructor' functionexp
stat:= 'class' derefexp ['extends' derefexp] '{'
[memberdecl]
'}'
creates a new class.
-----------
try/catch
-----------
.. index::
pair: try/catch; statement
::
stat:= 'try' stat 'catch' '(' id ')' stat
The try statement encloses a block of code in which an exceptional condition can occur,
such as a runtime error or a throw statement. The catch clause provides the exception-handling
code. When a catch clause catches an exception, its id is bound to that
exception.
-----------
throw
-----------
.. index::
pair: throw; statement
::
stat:= 'throw' exp
Throws an exception. Any value can be thrown.
--------------
const
--------------
.. index::
pair: const; statement
::
stat:= 'const' id '=' 'Integer | Float | StringLiteral
Declares a constant (see :ref:`Constants & Enumerations <constants_and_enumerations>`).
--------------
enum
--------------
.. index::
pair: enum; statement
::
enumerations := ( 'id' '=' Integer | Float | StringLiteral ) [',']
stat:= 'enum' id '{' enumerations '}'
Declares an enumeration (see :ref:`Constants & Enumerations <constants_and_enumerations>`).
--------------------
Expression statement
--------------------
.. index::
pair: Expression statement; statement
::
stat := exp
In Squirrel every expression is also allowed as statement, if so, the result of the
expression is thrown away.

View File

@ -0,0 +1,71 @@
.. _tables:
=================
Tables
=================
.. index::
single: Tables
Tables are associative containers implemented as pairs of key/value (called slot); values
can be any possible type and keys any type except 'null'.
Tables are squirrel's skeleton, delegation and many other features are all implemented
through this type; even the environment, where "global" variables are stored, is a table
(known as root table).
------------------
Construction
------------------
Tables are created through the table constructor (see :ref:`Table constructor <table_constructor>`)
------------------
Slot creation
------------------
.. index::
single: Slot Creation(table)
Adding a new slot in a existing table is done through the "new slot" operator ``<-``; this
operator behaves like a normal assignment except that if the slot does not exists it will
be created.::
local a = {}
The following line will cause an exception because the slot named 'newslot' does not exist
in the table 'a'::
a.newslot = 1234
this will succeed: ::
a.newslot <- 1234;
or::
a[1] <- "I'm the value of the new slot";
-----------------
Slot deletion
-----------------
.. index::
single: Slot Deletion(table)
::
exp:= delete derefexp
Deletion of a slot is done through the keyword delete; the result of this expression will be
the value of the deleted slot.::
a <- {
test1=1234
deleteme="now"
}
delete a.test1
print(delete a.deleteme); //this will print the string "now"

View File

@ -0,0 +1,106 @@
.. _threads:
========================
Threads
========================
.. index::
single: Threads
Squirrel supports cooperative threads(also known as coroutines).
A cooperative thread is a subroutine that can suspended in mid-execution and provide a value to the
caller without returning program flow, then its execution can be resumed later from the same
point where it was suspended.
At first look a Squirrel thread can be confused with a generator, in fact their behaviour is quite similar.
However while a generator runs in the caller stack and can suspend only the local routine stack a thread
has its own execution stack, global table and error handler; This allows a thread to suspend nested calls and
have it's own error policies.
------------------
Using threads
------------------
.. index::
single: Using Threads
Threads are created through the built-in function 'newthread(func)'; this function
gets as parameter a squirrel function and bind it to the new thread objects (will be the thread body).
The returned thread object is initially in 'idle' state. the thread can be started with the function
'threadobj.call()'; the parameters passed to 'call' are passed to the thread function.
A thread can be be suspended calling the function suspend(), when this happens the function
that wokeup(or started) the thread returns (If a parameter is passed to suspend() it will
be the return value of the wakeup function , if no parameter is passed the return value will be null).
A suspended thread can be resumed calling the function 'threadobj.wakeup', when this happens
the function that suspended the thread will return(if a parameter is passed to wakeup it will
be the return value of the suspend function, if no parameter is passed the return value will be null).
A thread terminates when its main function returns or when an unhandled exception occurs during its execution.::
function coroutine_test(a,b)
{
::print(a+" "+b+"\n");
local ret = ::suspend("suspend 1");
::print("the coroutine says "+ret+"\n");
ret = ::suspend("suspend 2");
::print("the coroutine says "+ret+"\n");
ret = ::suspend("suspend 3");
::print("the coroutine says "+ret+"\n");
return "I'm done"
}
local coro = ::newthread(coroutine_test);
local susparam = coro.call("test","coroutine"); //starts the coroutine
local i = 1;
do
{
::print("suspend passed ("+susparam+")\n")
susparam = coro.wakeup("ciao "+i);
++i;
}while(coro.getstatus()=="suspended")
::print("return passed ("+susparam+")\n")
the result of this program will be::
test coroutine
suspend passed (suspend 1)
the coroutine says ciao 1
suspend passed (suspend 2)
the coroutine says ciao 2
suspend passed (suspend 3)
the coroutine says ciao 3
return passed (I'm done).
the following is an interesting example of how threads and tail recursion
can be combined.::
function state1()
{
::suspend("state1");
return state2(); //tail call
}
function state2()
{
::suspend("state2");
return state3(); //tail call
}
function state3()
{
::suspend("state3");
return state1(); //tail call
}
local statethread = ::newthread(state1)
::print(statethread.call()+"\n");
for(local i = 0; i < 10000; i++)
::print(statethread.wakeup()+"\n");

View File

@ -0,0 +1,61 @@
.. _weak_references:
========================
Weak References
========================
.. index::
single: Weak References
The weak references allows the programmers to create references to objects without
influencing the lifetime of the object itself.
In squirrel Weak references are first-class objects created through the built-in method obj.weakref().
All types except null implement the weakref() method; however in bools, integers, and floats the method
simply returns the object itself(this because this types are always passed by value).
When a weak references is assigned to a container (table slot,array,class or
instance) is treated differently than other objects; When a container slot that hold a weak
reference is fetched, it always returns the value pointed by the weak reference instead of the weak
reference object. This allow the programmer to ignore the fact that the value handled is weak.
When the object pointed by weak reference is destroyed, the weak reference is automatically set to null.::
local t = {}
local a = ["first","second","third"]
//creates a weakref to the array and assigns it to a table slot
t.thearray <- a.weakref();
The table slot 'thearray' contains a weak reference to an array.
The following line prints "first", because tables(and all other containers) always return
the object pointed by a weak ref::
print(t.thearray[0]);
the only strong reference to the array is owned by the local variable 'a', so
because the following line assigns a integer to 'a' the array is destroyed.::
a = 123;
When an object pointed by a weak ref is destroyed the weak ref is automatically set to null,
so the following line will print "null".::
::print(typeof(t.thearray))
-----------------------------------
Handling weak references explicitly
-----------------------------------
If a weak reference is assigned to a local variable, then is treated as any other value.::
local t = {}
local weakobj = t.weakref();
the following line prints "weakref".::
::print(typeof(weakobj))
the object pointed by the weakref can be obtained through the built-in method weakref.ref().
The following line prints "table".::
::print(typeof(weakobj.ref()))

View File

@ -0,0 +1,39 @@
.. _stdlib:
#################################
Squirrel Standard Library 3.1
#################################
Copyright (c) 2003-2016 Alberto Demichelis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
.. toctree::
:maxdepth: 1
:numbered:
introduction.rst
stdiolib.rst
stdbloblib.rst
stdmathlib.rst
stdsystemlib.rst
stdstringlib.rst
stdauxlib.rst

View File

@ -0,0 +1,22 @@
.. _stdlib_introduction:
============
Introduction
============
The squirrel standard libraries consist in a set of modules implemented in C++.
While are not essential for the language, they provide a set of useful services that are
commonly used by a wide range of applications(file I/O, regular expressions, etc...),
plus they offer a foundation for developing additional libraries.
All libraries are implemented through the squirrel API and the ANSI C runtime library.
The modules are organized in the following way:
* I/O : input and output
* blob : binary buffers manipilation
* math : basic mathematical routines
* system : system access function
* string : string formatting and manipulation
* aux : auxiliary functions
The libraries can be registered independently,except for the IO library that depends from the bloblib.

View File

@ -0,0 +1,31 @@
.. _stdlib_stdauxlib:
===============
The Aux library
===============
The aux library implements default handlers for compiler and runtime errors and a stack dumping.
+++++++++++
C API
+++++++++++
.. _sqstd_seterrorhandlers:
.. c:function:: void sqstd_seterrorhandlers(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
initialize compiler and runtime error handlers, the handlers
use the print function set through(:ref:`sq_setprintfunc <sq_setprintfunc>`) to output
the error.
.. _sqstd_printcallstack:
.. c:function:: void sqstd_printcallstack(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
prints the call stack and stack contents. the function
uses the print function set through(:ref:`sq_setprintfunc <sq_setprintfunc>`) to output
the stack dump.

View File

@ -0,0 +1,213 @@
.. _stdlib_stdbloblib:
==================
The Blob library
==================
The blob library implements binary data manipulations routines. The library is
based on `blob objects` that represent a buffer of arbitrary
binary data.
---------------
Squirrel API
---------------
+++++++++++++++
Global symbols
+++++++++++++++
.. js:function:: castf2i(f)
casts a float to a int
.. js:function:: casti2f(n)
casts a int to a float
.. js:function:: swap2(n)
swap the byte order of a number (like it would be a 16bits integer)
.. js:function:: swap4(n)
swap the byte order of an integer
.. js:function:: swapfloat(n)
swaps the byteorder of a float
++++++++++++++++++
The blob class
++++++++++++++++++
The blob object is a buffer of arbitrary binary data. The object behaves like
a file stream, it has a read/write pointer and it automatically grows if data
is written out of his boundary.
A blob can also be accessed byte by byte through the `[]` operator.
.. js:class:: blob(size)
:param int size: initial size of the blob
returns a new instance of a blob class of the specified size in bytes
.. js:function:: blob.eos()
returns a non null value if the read/write pointer is at the end of the stream.
.. js:function:: blob.flush()
flushes the stream.return a value != null if succeded, otherwise returns null
.. js:function:: blob.len()
returns the length of the stream
.. js:function:: blob.readblob(size)
:param int size: number of bytes to read
read n bytes from the stream and returns them as blob
.. js:function:: blob.readn(type)
:param int type: type of the number to read
reads a number from the stream according to the type parameter.
`type` can have the following values:
+--------------+--------------------------------------------------------------------------------+----------------------+
| parameter | return description | return type |
+==============+================================================================================+======================+
| 'l' | processor dependent, 32bits on 32bits processors, 64bits on 64bits processors | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'i' | 32bits number | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 's' | 16bits signed integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'w' | 16bits unsigned integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'c' | 8bits signed integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'b' | 8bits unsigned integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'f' | 32bits float | float |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'd' | 64bits float | float |
+--------------+--------------------------------------------------------------------------------+----------------------+
.. js:function:: blob.resize(size)
:param int size: the new size of the blob in bytes
resizes the blob to the specified `size`
.. js:function:: blob.seek(offset [,origin])
:param int offset: indicates the number of bytes from `origin`.
:param int origin: origin of the seek
+--------------+-------------------------------------------+
| 'b' | beginning of the stream |
+--------------+-------------------------------------------+
| 'c' | current location |
+--------------+-------------------------------------------+
| 'e' | end of the stream |
+--------------+-------------------------------------------+
Moves the read/write pointer to a specified location.
.. note:: If origin is omitted the parameter is defaulted as 'b'(beginning of the stream).
.. js:function:: blob.swap2()
swaps the byte order of the blob content as it would be an array of `16bits integers`
.. js:function:: blob.swap4()
swaps the byte order of the blob content as it would be an array of `32bits integers`
.. js:function:: blob.tell()
returns the read/write pointer absolute position
.. js:function:: blob.writeblob(src)
:param blob src: the source blob containing the data to be written
writes a blob in the stream
.. js:function:: blob.writen(n, type)
:param number n: the value to be written
:param int type: type of the number to write
writes a number in the stream formatted according to the `type` parameter
`type` can have the following values:
+--------------+--------------------------------------------------------------------------------+
| parameter | return description |
+==============+================================================================================+
| 'i' | 32bits number |
+--------------+--------------------------------------------------------------------------------+
| 's' | 16bits signed integer |
+--------------+--------------------------------------------------------------------------------+
| 'w' | 16bits unsigned integer |
+--------------+--------------------------------------------------------------------------------+
| 'c' | 8bits signed integer |
+--------------+--------------------------------------------------------------------------------+
| 'b' | 8bits unsigned integer |
+--------------+--------------------------------------------------------------------------------+
| 'f' | 32bits float |
+--------------+--------------------------------------------------------------------------------+
| 'd' | 64bits float |
+--------------+--------------------------------------------------------------------------------+
------
C API
------
.. _sqstd_register_bloblib:
.. c:function:: SQRESULT sqstd_register_bloblib(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an SQRESULT
:remarks: The function aspects a table on top of the stack where to register the global library functions.
initializes and registers the blob library in the given VM.
.. _sqstd_getblob:
.. c:function:: SQRESULT sqstd_getblob(HSQUIRRELVM v, SQInteger idx, SQUserPointer* ptr)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: and index in the stack
:param SQUserPointer* ptr: A pointer to the userpointer that will point to the blob's payload
:returns: an SQRESULT
retrieve the pointer of a blob's payload from an arbitrary
position in the stack.
.. _sqstd_getblobsize:
.. c:function:: SQInteger sqstd_getblobsize(HSQUIRRELVM v, SQInteger idx)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: and index in the stack
:returns: the size of the blob at `idx` position
retrieves the size of a blob's payload from an arbitrary
position in the stack.
.. _sqstd_createblob:
.. c:function:: SQUserPointer sqstd_createblob(HSQUIRRELVM v, SQInteger size)
:param HSQUIRRELVM v: the target VM
:param SQInteger size: the size of the blob payload that has to be created
:returns: a pointer to the newly created blob payload
creates a blob with the given payload size and pushes it in the stack.

View File

@ -0,0 +1,264 @@
.. _stdlib_stdiolib:
========================
The Input/Output library
========================
the i/o library implements basic input/output routines.
--------------
Squirrel API
--------------
++++++++++++++
Global Symbols
++++++++++++++
.. js:function:: dofile(path, [raiseerror])
compiles a squirrel script or loads a precompiled one and executes it.
returns the value returned by the script or null if no value is returned.
if the optional parameter 'raiseerror' is true, the compiler error handler is invoked
in case of a syntax error. If raiseerror is omitted or set to false, the compiler
error handler is not invoked.
When squirrel is compiled in Unicode mode the function can handle different character encodings,
UTF8 with and without prefix and UCS-2 prefixed(both big endian an little endian).
If the source stream is not prefixed UTF8 encoding is used as default.
.. js:function:: loadfile(path, [raiseerror])
compiles a squirrel script or loads a precompiled one an returns it as as function.
if the optional parameter 'raiseerror' is true, the compiler error handler is invoked
in case of a syntax error. If raiseerror is omitted or set to false, the compiler
error handler is not invoked.
When squirrel is compiled in Unicode mode the function can handle different character encodings,
UTF8 with and without prefix and UCS-2 prefixed(both big endian an little endian).
If the source stream is not prefixed UTF8 encoding is used as default.
.. js:function:: writeclosuretofile(destpath, closure)
serializes a closure to a bytecode file (destpath). The serialized file can be loaded
using loadfile() and dofile().
.. js:data:: stderr
File object bound on the os *standard error* stream
.. js:data:: stdin
File object bound on the os *standard input* stream
.. js:data:: stdout
File object bound on the os *standard output* stream
++++++++++++++
The file class
++++++++++++++
The file object implements a stream on a operating system file.
.. js:class:: file(path, patten)
It's constructor imitates the behaviour of the C runtime function fopen for eg. ::
local myfile = file("test.xxx","wb+");
creates a file with read/write access in the current directory.
.. js:function:: file.close()
closes the file.
.. js:function:: file.eos()
returns a non null value if the read/write pointer is at the end of the stream.
.. js:function:: file.flush()
flushes the stream.return a value != null if succeeded, otherwise returns null
.. js:function:: file.len()
returns the length of the stream
.. js:function:: file.readblob(size)
:param int size: number of bytes to read
read n bytes from the stream and returns them as blob
.. js:function:: file.readn(type)
:param int type: type of the number to read
reads a number from the stream according to the type parameter.
`type` can have the following values:
+--------------+--------------------------------------------------------------------------------+----------------------+
| parameter | return description | return type |
+==============+================================================================================+======================+
| 'l' | processor dependent, 32bits on 32bits processors, 64bits on 64bits processors | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'i' | 32bits number | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 's' | 16bits signed integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'w' | 16bits unsigned integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'c' | 8bits signed integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'b' | 8bits unsigned integer | integer |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'f' | 32bits float | float |
+--------------+--------------------------------------------------------------------------------+----------------------+
| 'd' | 64bits float | float |
+--------------+--------------------------------------------------------------------------------+----------------------+
.. js:function:: file.resize(size)
:param int size: the new size of the blob in bytes
resizes the blob to the specified `size`
.. js:function:: file.seek(offset [,origin])
:param int offset: indicates the number of bytes from `origin`.
:param int origin: origin of the seek
+--------------+-------------------------------------------+
| 'b' | beginning of the stream |
+--------------+-------------------------------------------+
| 'c' | current location |
+--------------+-------------------------------------------+
| 'e' | end of the stream |
+--------------+-------------------------------------------+
Moves the read/write pointer to a specified location.
.. note:: If origin is omitted the parameter is defaulted as 'b'(beginning of the stream).
.. js:function:: file.tell()
returns the read/write pointer absolute position
.. js:function:: file.writeblob(src)
:param blob src: the source blob containing the data to be written
writes a blob in the stream
.. js:function:: file.writen(n, type)
:param number n: the value to be written
:param int type: type of the number to write
writes a number in the stream formatted according to the `type` pamraeter
`type` can have the following values:
+--------------+--------------------------------------------------------------------------------+
| parameter | return description |
+==============+================================================================================+
| 'i' | 32bits number |
+--------------+--------------------------------------------------------------------------------+
| 's' | 16bits signed integer |
+--------------+--------------------------------------------------------------------------------+
| 'w' | 16bits unsigned integer |
+--------------+--------------------------------------------------------------------------------+
| 'c' | 8bits signed integer |
+--------------+--------------------------------------------------------------------------------+
| 'b' | 8bits unsigned integer |
+--------------+--------------------------------------------------------------------------------+
| 'f' | 32bits float |
+--------------+--------------------------------------------------------------------------------+
| 'd' | 64bits float |
+--------------+--------------------------------------------------------------------------------+
--------------
C API
--------------
.. _sqstd_register_iolib:
.. c:function:: SQRESULT sqstd_register_iolib(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an SQRESULT
:remarks: The function aspects a table on top of the stack where to register the global library functions.
initialize and register the io library in the given VM.
++++++++++++++
File Object
++++++++++++++
.. c:function:: SQRESULT sqstd_createfile(HSQUIRRELVM v, SQFILE file, SQBool owns)
:param HSQUIRRELVM v: the target VM
:param SQFILE file: the stream that will be rapresented by the file object
:param SQBool owns: if different true the stream will be automatically closed when the newly create file object is destroyed.
:returns: an SQRESULT
creates a file object bound to the SQFILE passed as parameter
and pushes it in the stack
.. c:function:: SQRESULT sqstd_getfile(HSQUIRRELVM v, SQInteger idx, SQFILE* file)
:param HSQUIRRELVM v: the target VM
:param SQInteger idx: and index in the stack
:param SQFILE* file: A pointer to a SQFILE handle that will store the result
:returns: an SQRESULT
retrieve the pointer of a stream handle from an arbitrary
position in the stack.
++++++++++++++++++++++++++++++++
Script loading and serialization
++++++++++++++++++++++++++++++++
.. c:function:: SQRESULT sqstd_loadfile(HSQUIRRELVM v, const SQChar* filename, SQBool printerror)
:param HSQUIRRELVM v: the target VM
:param SQChar* filename: path of the script that has to be loaded
:param SQBool printerror: if true the compiler error handler will be called if a error occurs
:returns: an SQRESULT
Compiles a squirrel script or loads a precompiled one an pushes it as closure in the stack.
When squirrel is compiled in Unicode mode the function can handle different character encodings,
UTF8 with and without prefix and UCS-2 prefixed(both big endian an little endian).
If the source stream is not prefixed UTF8 encoding is used as default.
.. c:function:: SQRESULT sqstd_dofile(HSQUIRRELVM v, const SQChar* filename, SQBool retval, SQBool printerror)
:param HSQUIRRELVM v: the target VM
:param SQChar* filename: path of the script that has to be loaded
:param SQBool retval: if true the function will push the return value of the executed script in the stack.
:param SQBool printerror: if true the compiler error handler will be called if a error occurs
:returns: an SQRESULT
:remarks: the function expects a table on top of the stack that will be used as 'this' for the execution of the script. The 'this' parameter is left untouched in the stack.
Compiles a squirrel script or loads a precompiled one and executes it.
Optionally pushes the return value of the executed script in the stack.
When squirrel is compiled in unicode mode the function can handle different character encodings,
UTF8 with and without prefix and UCS-2 prefixed(both big endian an little endian).
If the source stream is not prefixed, UTF8 encoding is used as default. ::
sq_pushroottable(v); //push the root table(were the globals of the script will are stored)
sqstd_dofile(v, _SC("test.nut"), SQFalse, SQTrue);// also prints syntax errors if any
.. c:function:: SQRESULT sqstd_writeclosuretofile(HSQUIRRELVM v, const SQChar* filename)
:param HSQUIRRELVM v: the target VM
:param SQChar* filename: destination path of serialized closure
:returns: an SQRESULT
serializes the closure at the top position in the stack as bytecode in
the file specified by the parameter filename. If a file with the
same name already exists, it will be overwritten.

View File

@ -0,0 +1,111 @@
.. _stdlib_stdmathlib:
================
The Math library
================
the math lib provides basic mathematic routines. The library mimics the
C runtime library implementation.
------------
Squirrel API
------------
+++++++++++++++
Global Symbols
+++++++++++++++
.. js:function:: abs(x)
returns the absolute value of `x` as an integer
.. js:function:: acos(x)
returns the arccosine of `x`
.. js:function:: asin(x)
returns the arcsine of `x`
.. js:function:: atan(x)
returns the arctangent of `x`
.. js:function:: atan2(x,y)
returns the arctangent of `x/y`
.. js:function:: ceil(x)
returns a float value representing the smallest integer that is greater than or equal to `x`
.. js:function:: cos(x)
returns the cosine of `x`
.. js:function:: exp(x)
returns the exponential value of the float parameter `x`
.. js:function:: fabs(x)
returns the absolute value of `x` as a float
.. js:function:: floor(x)
returns a float value representing the largest integer that is less than or equal to `x`
.. js:function:: log(x)
returns the natural logarithm of `x`
.. js:function:: log10(x)
returns the logarithm base-10 of `x`
.. js:function:: pow(x,y)
returns `x` raised to the power of `y`
.. js:function:: rand()
returns a pseudorandom integer in the range 0 to `RAND_MAX`
.. js:function:: sin(x)
rreturns the sine of `x`
.. js:function:: sqrt(x)
returns the square root of `x`
.. js:function:: srand(seed)
sets the starting point for generating a series of pseudorandom integers
.. js:function:: tan(x)
returns the tangent of `x`
.. js:data:: RAND_MAX
the maximum value that can be returned by the `rand()` function
.. js:data:: PI
The numeric constant pi (3.141592) is the ratio of the circumference of a circle to its diameter
------------
C API
------------
.. _sqstd_register_mathlib:
.. c:function:: SQRESULT sqstd_register_mathlib(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an SQRESULT
:remarks: The function aspects a table on top of the stack where to register the global library functions.
initializes and register the math library in the given VM.

View File

@ -0,0 +1,319 @@
.. _stdlib_stdstringlib:
==================
The String library
==================
the string lib implements string formatting and regular expression matching routines.
--------------
Squirrel API
--------------
++++++++++++++
Global Symbols
++++++++++++++
.. js:function:: endswith(str, cmp)
returns `true` if the end of the string `str` matches a the string `cmp` otherwise returns `false`
.. js:function:: escape(str)
Returns a string with backslashes before characters that need to be escaped(`\",\a,\b,\t,\n,\v,\f,\r,\\,\",\',\0,\xnn`).
.. js:function:: format(formatstr, ...)
Returns a string formatted according `formatstr` and the optional parameters following it.
The format string follows the same rules as the `printf` family of
standard C functions( the "*" is not supported). ::
e.g.
sq> print(format("%s %d 0x%02X\n","this is a test :",123,10));
this is a test : 123 0x0A
.. js:function:: printf(formatstr, ...)
Just like calling `print(format(formatstr` as in the example above, but is more convenient AND more efficient. ::
e.g.
sq> printf("%s %d 0x%02X\n","this is a test :",123,10);
this is a test : 123 0x0A
.. js:function:: lstrip(str)
Strips white-space-only characters that might appear at the beginning of the given string
and returns the new stripped string.
.. js:function:: rstrip(str)
Strips white-space-only characters that might appear at the end of the given string
and returns the new stripped string.
.. js:function:: split(str, separators)
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.
::
eg.
local a = split("1.2-3;4/5",".-/;");
// the result will be [1,2,3,4,5]
.. js:function:: startswith(str, cmp)
returns `true` if the beginning of the string `str` matches the string `cmp`; otherwise returns `false`
.. js:function:: strip(str)
Strips white-space-only characters that might appear at the beginning or end of the given string and returns the new stripped string.
++++++++++++++++++
The regexp class
++++++++++++++++++
.. js:class:: regexp(pattern)
The regexp object represents a precompiled regular expression pattern. The object is created
through `regexp(pattern)`.
+---------------------+--------------------------------------+
| `\\` | Quote the next metacharacter |
+---------------------+--------------------------------------+
| `^` | Match the beginning of the string |
+---------------------+--------------------------------------+
| `.` | Match any character |
+---------------------+--------------------------------------+
| `$` | Match the end of the string |
+---------------------+--------------------------------------+
| `|` | Alternation |
+---------------------+--------------------------------------+
| `(subexp)` | Grouping (creates a capture) |
+---------------------+--------------------------------------+
| `(?:subexp)` | No Capture Grouping (no capture) |
+---------------------+--------------------------------------+
| `[]` | Character class |
+---------------------+--------------------------------------+
**GREEDY CLOSURES**
+---------------------+---------------------------------------------+
| `*` | Match 0 or more times |
+---------------------+---------------------------------------------+
| `+` | Match 1 or more times |
+---------------------+---------------------------------------------+
| `?` | Match 1 or 0 times |
+---------------------+---------------------------------------------+
| `{n}` | Match exactly n times |
+---------------------+---------------------------------------------+
| `{n,}` | Match at least n times |
+---------------------+---------------------------------------------+
| `{n,m}` | Match at least n but not more than m times |
+---------------------+---------------------------------------------+
**ESCAPE CHARACTERS**
+---------------------+--------------------------------------+
| `\\t` | tab (HT, TAB) |
+---------------------+--------------------------------------+
| `\\n` | newline (LF, NL) |
+---------------------+--------------------------------------+
| `\\r` | return (CR) |
+---------------------+--------------------------------------+
| `\\f` | form feed (FF) |
+---------------------+--------------------------------------+
**PREDEFINED CLASSES**
+---------------------+--------------------------------------+
| `\\l` | lowercase next char |
+---------------------+--------------------------------------+
| `\\u` | uppercase next char |
+---------------------+--------------------------------------+
| `\\a` | letters |
+---------------------+--------------------------------------+
| `\\A` | non letters |
+---------------------+--------------------------------------+
| `\\w` | alphanumeric `[_0-9a-zA-Z]` |
+---------------------+--------------------------------------+
| `\\W` | non alphanumeric `[^_0-9a-zA-Z]` |
+---------------------+--------------------------------------+
| `\\s` | space |
+---------------------+--------------------------------------+
| `\\S` | non space |
+---------------------+--------------------------------------+
| `\\d` | digits |
+---------------------+--------------------------------------+
| `\\D` | non digits |
+---------------------+--------------------------------------+
| `\\x` | hexadecimal digits |
+---------------------+--------------------------------------+
| `\\X` | non hexadecimal digits |
+---------------------+--------------------------------------+
| `\\c` | control characters |
+---------------------+--------------------------------------+
| `\\C` | non control characters |
+---------------------+--------------------------------------+
| `\\p` | punctuation |
+---------------------+--------------------------------------+
| `\\P` | non punctuation |
+---------------------+--------------------------------------+
| `\\b` | word boundary |
+---------------------+--------------------------------------+
| `\\B` | non word boundary |
+---------------------+--------------------------------------+
.. js:function:: regexp.capture(str [, start])
returns an array of tables containing two indexes ("begin" and "end") of
the first match of the regular expression in the string `str`.
An array entry is created for each captured sub expressions. If no match occurs returns null.
The search starts from the index `start`
of the string; if `start` is omitted the search starts from the beginning of the string.
The first element of the returned array(index 0) always contains the complete match.
::
local ex = regexp(@"(\d+) ([a-zA-Z]+)(\p)");
local string = "stuff 123 Test;";
local res = ex.capture(string);
foreach(i,val in res)
{
print(format("match number[%02d] %s\n",
i,string.slice(val.begin,val.end))); //prints "Test"
}
...
will print
match number[00] 123 Test;
match number[01] 123
match number[02] Test
match number[03] ;
.. js:function:: regexp.match(str)
returns a true if the regular expression matches the string
`str`, otherwise returns false.
.. js:function:: regexp.search(str [, start])
returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in
the string `str`, otherwise if no match occurs returns null. The search starts from the index `start`
of the string; if `start` is omitted the search starts from the beginning of the string.
::
local ex = regexp("[a-zA-Z]+");
local string = "123 Test;";
local res = ex.search(string);
print(string.slice(res.begin,res.end)); //prints "Test"
-------------
C API
-------------
.. _sqstd_register_stringlib:
.. c:function:: SQRESULT sqstd_register_stringlib(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an SQRESULT
:remarks: The function aspects a table on top of the stack where to register the global library functions.
initialize and register the string library in the given VM.
+++++++++++++
Formatting
+++++++++++++
.. c:function:: SQRESULT sqstd_format(HSQUIRRELVM v, SQInteger nformatstringidx, SQInteger* outlen, SQChar** output)
:param HSQUIRRELVM v: the target VM
:param SQInteger nformatstringidx: index in the stack of the format string
:param SQInteger* outlen: a pointer to an integer that will be filled with the length of the newly created string
:param SQChar** output: a pointer to a string pointer that will receive the newly created string
:returns: an SQRESULT
:remarks: the newly created string is allocated in the scratchpad memory.
creates a new string formatted according to the object at position `nformatstringidx` and the optional parameters following it.
The format string follows the same rules as the `printf` family of
standard C functions( the "*" is not supported).
++++++++++++++++++
Regular Expessions
++++++++++++++++++
.. c:function:: SQRex* sqstd_rex_compile(const SQChar *pattern, const SQChar ** error)
:param SQChar* pattern: a pointer to a zero terminated string containing the pattern that has to be compiled.
:param SQChar** error: a pointer to a string pointer that will be set with an error string in case of failure.
:returns: a pointer to the compiled pattern
compiles an expression and returns a pointer to the compiled version.
in case of failure returns NULL.The returned object has to be deleted
through the function sqstd_rex_free().
.. c:function:: void sqstd_rex_free(SQRex * exp)
:param SQRex* exp: the expression structure that has to be deleted.
deletes a expression structure created with sqstd_rex_compile()
.. c:function:: SQBool sqstd_rex_match(SQRex * exp,const SQChar * text)
:param SQRex* exp: a compiled expression
:param SQChar* text: the string that has to be tested
:returns: SQTrue if successful otherwise SQFalse
returns SQTrue if the string specified in the parameter text is an
exact match of the expression, otherwise returns SQFalse.
.. c:function:: SQBool sqstd_rex_search(SQRex * exp, const SQChar * text, const SQChar ** out_begin, const SQChar ** out_end)
:param SQRex* exp: a compiled expression
:param SQChar* text: the string that has to be tested
:param SQChar** out_begin: a pointer to a string pointer that will be set with the beginning of the match
:param SQChar** out_end: a pointer to a string pointer that will be set with the end of the match
:returns: SQTrue if successful otherwise SQFalse
searches the first match of the expression in the string specified in the parameter text.
if the match is found returns SQTrue and the sets out_begin to the beginning of the
match and out_end at the end of the match; otherwise returns SQFalse.
.. c:function:: SQBool sqstd_rex_searchrange(SQRex * exp, const SQChar * text_begin, const SQChar * text_end, const SQChar ** out_begin, const SQChar ** out_end)
:param SQRex* exp: a compiled expression
:param SQChar* text_begin: a pointer to the beginnning of the string that has to be tested
:param SQChar* text_end: a pointer to the end of the string that has to be tested
:param SQChar** out_begin: a pointer to a string pointer that will be set with the beginning of the match
:param SQChar** out_end: a pointer to a string pointer that will be set with the end of the match
:returns: SQTrue if successful otherwise SQFalse
searches the first match of the expression in the string delimited
by the parameter text_begin and text_end.
if the match is found returns SQTrue and sets out_begin to the beginning of the
match and out_end at the end of the match; otherwise returns SQFalse.
.. c:function:: SQInteger sqstd_rex_getsubexpcount(SQRex * exp)
:param SQRex* exp: a compiled expression
:returns: the number of sub expressions matched by the expression
returns the number of sub expressions matched by the expression
.. c:function:: SQBool sqstd_rex_getsubexp(SQRex * exp, SQInteger n, SQRexMatch *subexp)
:param SQRex* exp: a compiled expression
:param SQInteger n: the index of the submatch(0 is the complete match)
:param SQRexMatch* a: pointer to structure that will store the result
:returns: the function returns SQTrue if n is a valid index; otherwise SQFalse.
retrieve the begin and and pointer to the length of the sub expression indexed
by n. The result is passed through the struct SQRexMatch.

View File

@ -0,0 +1,82 @@
.. _stdlib_stdsystemlib:
==================
The System library
==================
The system library exposes operating system facilities like environment variables,
date time manipulation etc..
--------------
Squirrel API
--------------
++++++++++++++
Global Symbols
++++++++++++++
.. js:function:: clock()
returns a float representing the number of seconds elapsed since the start of the process
.. js:function:: date([time [, format]])
returns a table containing a date/time split into the slots:
+-------------+----------------------------------------+
| sec | Seconds after minute (0 - 59). |
+-------------+----------------------------------------+
| min | Minutes after hour (0 - 59). |
+-------------+----------------------------------------+
| hour | Hours since midnight (0 - 23). |
+-------------+----------------------------------------+
| day | Day of month (1 - 31). |
+-------------+----------------------------------------+
| month | Month (0 - 11; January = 0). |
+-------------+----------------------------------------+
| year | Year (current year). |
+-------------+----------------------------------------+
| wday | Day of week (0 - 6; Sunday = 0). |
+-------------+----------------------------------------+
| yday | Day of year (0 - 365; January 1 = 0). |
+-------------+----------------------------------------+
if `time` is omitted the current time is used.
if `format` can be 'l' local time or 'u' UTC time, if omitted is defaulted as 'l'(local time).
.. js:function:: getenv(varaname)
Returns a string containing the value of the environment variable `varname`
.. js:function:: remove(path)
deletes the file specified by `path`
.. js:function:: rename(oldname, newname)
renames the file or directory specified by `oldname` to the name given by `newname`
.. js:function:: system(cmd)
xecutes the string `cmd` through the os command interpreter.
.. js:function:: time()
returns the number of seconds elapsed since midnight 00:00:00, January 1, 1970.
the result of this function can be formatted through the function `date()`
--------------
C API
--------------
.. _sqstd_register_systemlib:
.. c:function:: SQRESULT sqstd_register_systemlib(HSQUIRRELVM v)
:param HSQUIRRELVM v: the target VM
:returns: an SQRESULT
:remarks: The function aspects a table on top of the stack where to register the global library functions.
initialize and register the system library in the given VM.

View File

@ -0,0 +1,78 @@
#include <stdarg.h>
#include <stdio.h>
#include <squirrel.h>
#include <sqstdio.h>
#include <sqstdaux.h>
#ifdef _MSC_VER
#pragma comment (lib ,"squirrel.lib")
#pragma comment (lib ,"sqstdlib.lib")
#endif
#ifdef SQUNICODE
#define scvprintf vfwprintf
#else
#define scvprintf vfprintf
#endif
void printfunc(HSQUIRRELVM v,const SQChar *s,...)
{
va_list vl;
va_start(vl, s);
scvprintf(stdout, s, vl);
va_end(vl);
}
void errorfunc(HSQUIRRELVM v,const SQChar *s,...)
{
va_list vl;
va_start(vl, s);
scvprintf(stderr, s, vl);
va_end(vl);
}
void call_foo(HSQUIRRELVM v, int n,float f,const SQChar *s)
{
SQInteger top = sq_gettop(v); //saves the stack size before the call
sq_pushroottable(v); //pushes the global table
sq_pushstring(v,_SC("foo"),-1);
if(SQ_SUCCEEDED(sq_get(v,-2))) { //gets the field 'foo' from the global table
sq_pushroottable(v); //push the 'this' (in this case is the global table)
sq_pushinteger(v,n);
sq_pushfloat(v,f);
sq_pushstring(v,s,-1);
sq_call(v,4,SQFalse,SQTrue); //calls the function
}
sq_settop(v,top); //restores the original stack size
}
int main(int argc, char* argv[])
{
HSQUIRRELVM v;
v = sq_open(1024); // creates a VM with initial stack size 1024
//REGISTRATION OF STDLIB
//sq_pushroottable(v); //push the root table where the std function will be registered
//sqstd_register_iolib(v); //registers a library
// ... call here other stdlibs string,math etc...
//sq_pop(v,1); //pops the root table
//END REGISTRATION OF STDLIB
sqstd_seterrorhandlers(v); //registers the default error handlers
sq_setprintfunc(v, printfunc,errorfunc); //sets the print function
sq_pushroottable(v); //push the root table(were the globals of the script will be stored)
if(SQ_SUCCEEDED(sqstd_dofile(v, _SC("test.nut"), SQFalse, SQTrue))) // also prints syntax errors if any
{
call_foo(v,1,2.5,_SC("teststring"));
}
sq_pop(v,1); //pops the root table
sq_close(v);
return 0;
}

View File

@ -0,0 +1,4 @@
function foo(i, f, s)
{
print("Called foo(), i="+i+", f="+f+", s='"+s+"'\n");
}

View File

@ -0,0 +1,146 @@
#ifdef _SQ64
#ifdef _MSC_VER
typedef __int64 SQInteger;
typedef unsigned __int64 SQUnsignedInteger;
typedef unsigned __int64 SQHash; /*should be the same size of a pointer*/
#else
typedef long long SQInteger;
typedef unsigned long long SQUnsignedInteger;
typedef unsigned long long SQHash; /*should be the same size of a pointer*/
#endif
typedef int SQInt32;
typedef unsigned int SQUnsignedInteger32;
#else
typedef int SQInteger;
typedef int SQInt32; /*must be 32 bits(also on 64bits processors)*/
typedef unsigned int SQUnsignedInteger32; /*must be 32 bits(also on 64bits processors)*/
typedef unsigned int SQUnsignedInteger;
typedef unsigned int SQHash; /*should be the same size of a pointer*/
#endif
#ifdef SQUSEDOUBLE
typedef double SQFloat;
#else
typedef float SQFloat;
#endif
#if defined(SQUSEDOUBLE) && !defined(_SQ64) || !defined(SQUSEDOUBLE) && defined(_SQ64)
#ifdef _MSC_VER
typedef __int64 SQRawObjectVal; //must be 64bits
#else
typedef long long SQRawObjectVal; //must be 64bits
#endif
#define SQ_OBJECT_RAWINIT() { _unVal.raw = 0; }
#else
typedef SQUnsignedInteger SQRawObjectVal; //is 32 bits on 32 bits builds and 64 bits otherwise
#define SQ_OBJECT_RAWINIT()
#endif
#ifndef SQ_ALIGNMENT // SQ_ALIGNMENT shall be less than or equal to SQ_MALLOC alignments, and its value shall be power of 2.
#if defined(SQUSEDOUBLE) || defined(_SQ64)
#define SQ_ALIGNMENT 8
#else
#define SQ_ALIGNMENT 4
#endif
#endif
typedef void* SQUserPointer;
typedef SQUnsignedInteger SQBool;
typedef SQInteger SQRESULT;
#ifdef SQUNICODE
#include <wchar.h>
#include <wctype.h>
typedef wchar_t SQChar;
#define scstrcmp wcscmp
#ifdef _WIN32
#define scsprintf _snwprintf
#else
#define scsprintf swprintf
#endif
#define scstrlen wcslen
#define scstrtod wcstod
#ifdef _SQ64
#define scstrtol wcstoll
#else
#define scstrtol wcstol
#endif
#define scstrtoul wcstoul
#define scvsprintf vswprintf
#define scstrstr wcsstr
#define scprintf wprintf
#ifdef _WIN32
#define WCHAR_SIZE 2
#define WCHAR_SHIFT_MUL 1
#define MAX_CHAR 0xFFFF
#else
#define WCHAR_SIZE 4
#define WCHAR_SHIFT_MUL 2
#define MAX_CHAR 0xFFFFFFFF
#endif
#define _SC(a) L##a
#define scisspace iswspace
#define scisdigit iswdigit
#define scisprint iswprint
#define scisxdigit iswxdigit
#define scisalpha iswalpha
#define sciscntrl iswcntrl
#define scisalnum iswalnum
#define sq_rsl(l) ((l)<<WCHAR_SHIFT_MUL)
#else
typedef char SQChar;
#define _SC(a) a
#define scstrcmp strcmp
#ifdef _MSC_VER
#define scsprintf _snprintf
#else
#define scsprintf snprintf
#endif
#define scstrlen strlen
#define scstrtod strtod
#ifdef _SQ64
#ifdef _MSC_VER
#define scstrtol _strtoi64
#else
#define scstrtol strtoll
#endif
#else
#define scstrtol strtol
#endif
#define scstrtoul strtoul
#define scvsprintf vsnprintf
#define scstrstr strstr
#define scisspace isspace
#define scisdigit isdigit
#define scisprint isprint
#define scisxdigit isxdigit
#define sciscntrl iscntrl
#define scisalpha isalpha
#define scisalnum isalnum
#define scprintf printf
#define MAX_CHAR 0xFF
#define sq_rsl(l) (l)
#endif
#ifdef _SQ64
#define _PRINT_INT_PREC _SC("ll")
#define _PRINT_INT_FMT _SC("%lld")
#else
#define _PRINT_INT_FMT _SC("%d")
#endif

View File

@ -0,0 +1,18 @@
/* see copyright notice in squirrel.h */
#ifndef _SQSTD_AUXLIB_H_
#define _SQSTD_AUXLIB_H_
#ifdef __cplusplus
extern "C" {
#endif
SQUIRREL_API void sqstd_seterrorhandlers(HSQUIRRELVM v);
SQUIRREL_API void sqstd_printcallstack(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sqstd_throwerrorf(HSQUIRRELVM v,const SQChar *err,...);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /* _SQSTD_AUXLIB_H_ */

View File

@ -0,0 +1,20 @@
/* see copyright notice in squirrel.h */
#ifndef _SQSTDBLOB_H_
#define _SQSTDBLOB_H_
#ifdef __cplusplus
extern "C" {
#endif
SQUIRREL_API SQUserPointer sqstd_createblob(HSQUIRRELVM v, SQInteger size);
SQUIRREL_API SQRESULT sqstd_getblob(HSQUIRRELVM v,SQInteger idx,SQUserPointer *ptr);
SQUIRREL_API SQInteger sqstd_getblobsize(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sqstd_register_bloblib(HSQUIRRELVM v);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*_SQSTDBLOB_H_*/

View File

@ -0,0 +1,54 @@
/* see copyright notice in squirrel.h */
#ifndef _SQSTDIO_H_
#define _SQSTDIO_H_
#ifdef __cplusplus
#define SQSTD_STREAM_TYPE_TAG 0x80000000
struct SQStream {
virtual ~SQStream() {}
virtual SQInteger Read(void *buffer, SQInteger size) = 0;
virtual SQInteger Write(void *buffer, SQInteger size) = 0;
virtual SQInteger Flush() = 0;
virtual SQInteger Tell() = 0;
virtual SQInteger Len() = 0;
virtual SQInteger Seek(SQInteger offset, SQInteger origin) = 0;
virtual bool IsValid() = 0;
virtual bool EOS() = 0;
};
extern "C" {
#endif
#define SQ_SEEK_CUR 0
#define SQ_SEEK_END 1
#define SQ_SEEK_SET 2
typedef void* SQFILE;
SQUIRREL_API SQFILE sqstd_fopen(const SQChar *,const SQChar *);
SQUIRREL_API SQInteger sqstd_fread(SQUserPointer, SQInteger, SQInteger, SQFILE);
SQUIRREL_API SQInteger sqstd_fwrite(const SQUserPointer, SQInteger, SQInteger, SQFILE);
SQUIRREL_API SQInteger sqstd_fseek(SQFILE , SQInteger , SQInteger);
SQUIRREL_API SQInteger sqstd_ftell(SQFILE);
SQUIRREL_API SQInteger sqstd_fflush(SQFILE);
SQUIRREL_API SQInteger sqstd_fclose(SQFILE);
SQUIRREL_API SQInteger sqstd_feof(SQFILE);
SQUIRREL_API SQRESULT sqstd_createfile(HSQUIRRELVM v, SQFILE file,SQBool own);
SQUIRREL_API SQRESULT sqstd_getfile(HSQUIRRELVM v, SQInteger idx, SQFILE *file);
//compiler helpers
SQUIRREL_API SQRESULT sqstd_loadfile(HSQUIRRELVM v,const SQChar *filename,SQBool printerror);
SQUIRREL_API SQRESULT sqstd_dofile(HSQUIRRELVM v,const SQChar *filename,SQBool retval,SQBool printerror);
SQUIRREL_API SQRESULT sqstd_writeclosuretofile(HSQUIRRELVM v,const SQChar *filename);
SQUIRREL_API SQRESULT sqstd_register_iolib(HSQUIRRELVM v);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*_SQSTDIO_H_*/

View File

@ -0,0 +1,15 @@
/* see copyright notice in squirrel.h */
#ifndef _SQSTD_MATH_H_
#define _SQSTD_MATH_H_
#ifdef __cplusplus
extern "C" {
#endif
SQUIRREL_API SQRESULT sqstd_register_mathlib(HSQUIRRELVM v);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*_SQSTD_MATH_H_*/

View File

@ -0,0 +1,35 @@
/* see copyright notice in squirrel.h */
#ifndef _SQSTD_STRING_H_
#define _SQSTD_STRING_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned int SQRexBool;
typedef struct SQRex SQRex;
typedef struct {
const SQChar *begin;
SQInteger len;
} SQRexMatch;
SQUIRREL_API SQRex *sqstd_rex_compile(const SQChar *pattern,const SQChar **error);
SQUIRREL_API void sqstd_rex_free(SQRex *exp);
SQUIRREL_API SQBool sqstd_rex_match(SQRex* exp,const SQChar* text);
SQUIRREL_API SQBool sqstd_rex_search(SQRex* exp,const SQChar* text, const SQChar** out_begin, const SQChar** out_end);
SQUIRREL_API SQBool sqstd_rex_searchrange(SQRex* exp,const SQChar* text_begin,const SQChar* text_end,const SQChar** out_begin, const SQChar** out_end);
SQUIRREL_API SQInteger sqstd_rex_getsubexpcount(SQRex* exp);
SQUIRREL_API SQBool sqstd_rex_getsubexp(SQRex* exp, SQInteger n, SQRexMatch *subexp);
SQUIRREL_API SQRESULT sqstd_format(HSQUIRRELVM v,SQInteger nformatstringidx,SQInteger *outlen,SQChar **output);
SQUIRREL_API void sqstd_pushstringf(HSQUIRRELVM v,const SQChar *s,...);
SQUIRREL_API SQRESULT sqstd_register_stringlib(HSQUIRRELVM v);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*_SQSTD_STRING_H_*/

View File

@ -0,0 +1,15 @@
/* see copyright notice in squirrel.h */
#ifndef _SQSTD_SYSTEMLIB_H_
#define _SQSTD_SYSTEMLIB_H_
#ifdef __cplusplus
extern "C" {
#endif
SQUIRREL_API SQInteger sqstd_register_systemlib(HSQUIRRELVM v);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /* _SQSTD_SYSTEMLIB_H_ */

View File

@ -0,0 +1,411 @@
/*
Copyright (c) 2003-2017 Alberto Demichelis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _SQUIRREL_H_
#define _SQUIRREL_H_
#ifdef _SQ_CONFIG_INCLUDE
#include _SQ_CONFIG_INCLUDE
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef SQUIRREL_API
#define SQUIRREL_API extern
#endif
#if (defined(_WIN64) || defined(_LP64))
#ifndef _SQ64
#define _SQ64
#endif
#endif
#define SQTrue (1)
#define SQFalse (0)
struct SQVM;
struct SQTable;
struct SQArray;
struct SQString;
struct SQClosure;
struct SQGenerator;
struct SQNativeClosure;
struct SQUserData;
struct SQFunctionProto;
struct SQRefCounted;
struct SQClass;
struct SQInstance;
struct SQDelegable;
struct SQOuter;
#ifdef _UNICODE
#define SQUNICODE
#endif
#include "sqconfig.h"
#define SQUIRREL_VERSION _SC("Squirrel 3.1 stable")
#define SQUIRREL_COPYRIGHT _SC("Copyright (C) 2003-2017 Alberto Demichelis")
#define SQUIRREL_AUTHOR _SC("Alberto Demichelis")
#define SQUIRREL_VERSION_NUMBER 310
#define SQ_VMSTATE_IDLE 0
#define SQ_VMSTATE_RUNNING 1
#define SQ_VMSTATE_SUSPENDED 2
#define SQUIRREL_EOB 0
#define SQ_BYTECODE_STREAM_TAG 0xFAFA
#define SQOBJECT_REF_COUNTED 0x08000000
#define SQOBJECT_NUMERIC 0x04000000
#define SQOBJECT_DELEGABLE 0x02000000
#define SQOBJECT_CANBEFALSE 0x01000000
#define SQ_MATCHTYPEMASKSTRING (-99999)
#define _RT_MASK 0x00FFFFFF
#define _RAW_TYPE(type) (type&_RT_MASK)
#define _RT_NULL 0x00000001
#define _RT_INTEGER 0x00000002
#define _RT_FLOAT 0x00000004
#define _RT_BOOL 0x00000008
#define _RT_STRING 0x00000010
#define _RT_TABLE 0x00000020
#define _RT_ARRAY 0x00000040
#define _RT_USERDATA 0x00000080
#define _RT_CLOSURE 0x00000100
#define _RT_NATIVECLOSURE 0x00000200
#define _RT_GENERATOR 0x00000400
#define _RT_USERPOINTER 0x00000800
#define _RT_THREAD 0x00001000
#define _RT_FUNCPROTO 0x00002000
#define _RT_CLASS 0x00004000
#define _RT_INSTANCE 0x00008000
#define _RT_WEAKREF 0x00010000
#define _RT_OUTER 0x00020000
typedef enum tagSQObjectType{
OT_NULL = (_RT_NULL|SQOBJECT_CANBEFALSE),
OT_INTEGER = (_RT_INTEGER|SQOBJECT_NUMERIC|SQOBJECT_CANBEFALSE),
OT_FLOAT = (_RT_FLOAT|SQOBJECT_NUMERIC|SQOBJECT_CANBEFALSE),
OT_BOOL = (_RT_BOOL|SQOBJECT_CANBEFALSE),
OT_STRING = (_RT_STRING|SQOBJECT_REF_COUNTED),
OT_TABLE = (_RT_TABLE|SQOBJECT_REF_COUNTED|SQOBJECT_DELEGABLE),
OT_ARRAY = (_RT_ARRAY|SQOBJECT_REF_COUNTED),
OT_USERDATA = (_RT_USERDATA|SQOBJECT_REF_COUNTED|SQOBJECT_DELEGABLE),
OT_CLOSURE = (_RT_CLOSURE|SQOBJECT_REF_COUNTED),
OT_NATIVECLOSURE = (_RT_NATIVECLOSURE|SQOBJECT_REF_COUNTED),
OT_GENERATOR = (_RT_GENERATOR|SQOBJECT_REF_COUNTED),
OT_USERPOINTER = _RT_USERPOINTER,
OT_THREAD = (_RT_THREAD|SQOBJECT_REF_COUNTED) ,
OT_FUNCPROTO = (_RT_FUNCPROTO|SQOBJECT_REF_COUNTED), //internal usage only
OT_CLASS = (_RT_CLASS|SQOBJECT_REF_COUNTED),
OT_INSTANCE = (_RT_INSTANCE|SQOBJECT_REF_COUNTED|SQOBJECT_DELEGABLE),
OT_WEAKREF = (_RT_WEAKREF|SQOBJECT_REF_COUNTED),
OT_OUTER = (_RT_OUTER|SQOBJECT_REF_COUNTED) //internal usage only
}SQObjectType;
#define ISREFCOUNTED(t) (t&SQOBJECT_REF_COUNTED)
typedef union tagSQObjectValue
{
struct SQTable *pTable;
struct SQArray *pArray;
struct SQClosure *pClosure;
struct SQOuter *pOuter;
struct SQGenerator *pGenerator;
struct SQNativeClosure *pNativeClosure;
struct SQString *pString;
struct SQUserData *pUserData;
SQInteger nInteger;
SQFloat fFloat;
SQUserPointer pUserPointer;
struct SQFunctionProto *pFunctionProto;
struct SQRefCounted *pRefCounted;
struct SQDelegable *pDelegable;
struct SQVM *pThread;
struct SQClass *pClass;
struct SQInstance *pInstance;
struct SQWeakRef *pWeakRef;
SQRawObjectVal raw;
}SQObjectValue;
typedef struct tagSQObject
{
SQObjectType _type;
SQObjectValue _unVal;
}SQObject;
typedef struct tagSQMemberHandle{
SQBool _static;
SQInteger _index;
}SQMemberHandle;
typedef struct tagSQStackInfos{
const SQChar* funcname;
const SQChar* source;
SQInteger line;
}SQStackInfos;
typedef struct SQVM* HSQUIRRELVM;
typedef SQObject HSQOBJECT;
typedef SQMemberHandle HSQMEMBERHANDLE;
typedef SQInteger (*SQFUNCTION)(HSQUIRRELVM);
typedef SQInteger (*SQRELEASEHOOK)(SQUserPointer,SQInteger size);
typedef void (*SQCOMPILERERROR)(HSQUIRRELVM,const SQChar * /*desc*/,const SQChar * /*source*/,SQInteger /*line*/,SQInteger /*column*/);
typedef void (*SQPRINTFUNCTION)(HSQUIRRELVM,const SQChar * ,...);
typedef void (*SQDEBUGHOOK)(HSQUIRRELVM /*v*/, SQInteger /*type*/, const SQChar * /*sourcename*/, SQInteger /*line*/, const SQChar * /*funcname*/);
typedef SQInteger (*SQWRITEFUNC)(SQUserPointer,SQUserPointer,SQInteger);
typedef SQInteger (*SQREADFUNC)(SQUserPointer,SQUserPointer,SQInteger);
typedef SQInteger (*SQLEXREADFUNC)(SQUserPointer);
typedef struct tagSQRegFunction{
const SQChar *name;
SQFUNCTION f;
SQInteger nparamscheck;
const SQChar *typemask;
}SQRegFunction;
typedef struct tagSQFunctionInfo {
SQUserPointer funcid;
const SQChar *name;
const SQChar *source;
SQInteger line;
}SQFunctionInfo;
/*vm*/
SQUIRREL_API HSQUIRRELVM sq_open(SQInteger initialstacksize);
SQUIRREL_API HSQUIRRELVM sq_newthread(HSQUIRRELVM friendvm, SQInteger initialstacksize);
SQUIRREL_API void sq_seterrorhandler(HSQUIRRELVM v);
SQUIRREL_API void sq_close(HSQUIRRELVM v);
SQUIRREL_API void sq_setforeignptr(HSQUIRRELVM v,SQUserPointer p);
SQUIRREL_API SQUserPointer sq_getforeignptr(HSQUIRRELVM v);
SQUIRREL_API void sq_setsharedforeignptr(HSQUIRRELVM v,SQUserPointer p);
SQUIRREL_API SQUserPointer sq_getsharedforeignptr(HSQUIRRELVM v);
SQUIRREL_API void sq_setvmreleasehook(HSQUIRRELVM v,SQRELEASEHOOK hook);
SQUIRREL_API SQRELEASEHOOK sq_getvmreleasehook(HSQUIRRELVM v);
SQUIRREL_API void sq_setsharedreleasehook(HSQUIRRELVM v,SQRELEASEHOOK hook);
SQUIRREL_API SQRELEASEHOOK sq_getsharedreleasehook(HSQUIRRELVM v);
SQUIRREL_API void sq_setprintfunc(HSQUIRRELVM v, SQPRINTFUNCTION printfunc,SQPRINTFUNCTION errfunc);
SQUIRREL_API SQPRINTFUNCTION sq_getprintfunc(HSQUIRRELVM v);
SQUIRREL_API SQPRINTFUNCTION sq_geterrorfunc(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_suspendvm(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_wakeupvm(HSQUIRRELVM v,SQBool resumedret,SQBool retval,SQBool raiseerror,SQBool throwerror);
SQUIRREL_API SQInteger sq_getvmstate(HSQUIRRELVM v);
SQUIRREL_API SQInteger sq_getversion();
/*compiler*/
SQUIRREL_API SQRESULT sq_compile(HSQUIRRELVM v,SQLEXREADFUNC read,SQUserPointer p,const SQChar *sourcename,SQBool raiseerror);
SQUIRREL_API SQRESULT sq_compilebuffer(HSQUIRRELVM v,const SQChar *s,SQInteger size,const SQChar *sourcename,SQBool raiseerror);
SQUIRREL_API void sq_enabledebuginfo(HSQUIRRELVM v, SQBool enable);
SQUIRREL_API void sq_notifyallexceptions(HSQUIRRELVM v, SQBool enable);
SQUIRREL_API void sq_setcompilererrorhandler(HSQUIRRELVM v,SQCOMPILERERROR f);
/*stack operations*/
SQUIRREL_API void sq_push(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API void sq_pop(HSQUIRRELVM v,SQInteger nelemstopop);
SQUIRREL_API void sq_poptop(HSQUIRRELVM v);
SQUIRREL_API void sq_remove(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQInteger sq_gettop(HSQUIRRELVM v);
SQUIRREL_API void sq_settop(HSQUIRRELVM v,SQInteger newtop);
SQUIRREL_API SQRESULT sq_reservestack(HSQUIRRELVM v,SQInteger nsize);
SQUIRREL_API SQInteger sq_cmp(HSQUIRRELVM v);
SQUIRREL_API void sq_move(HSQUIRRELVM dest,HSQUIRRELVM src,SQInteger idx);
/*object creation handling*/
SQUIRREL_API SQUserPointer sq_newuserdata(HSQUIRRELVM v,SQUnsignedInteger size);
SQUIRREL_API void sq_newtable(HSQUIRRELVM v);
SQUIRREL_API void sq_newtableex(HSQUIRRELVM v,SQInteger initialcapacity);
SQUIRREL_API void sq_newarray(HSQUIRRELVM v,SQInteger size);
SQUIRREL_API void sq_newclosure(HSQUIRRELVM v,SQFUNCTION func,SQUnsignedInteger nfreevars);
SQUIRREL_API SQRESULT sq_setparamscheck(HSQUIRRELVM v,SQInteger nparamscheck,const SQChar *typemask);
SQUIRREL_API SQRESULT sq_bindenv(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_setclosureroot(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_getclosureroot(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API void sq_pushstring(HSQUIRRELVM v,const SQChar *s,SQInteger len);
SQUIRREL_API void sq_pushfloat(HSQUIRRELVM v,SQFloat f);
SQUIRREL_API void sq_pushinteger(HSQUIRRELVM v,SQInteger n);
SQUIRREL_API void sq_pushbool(HSQUIRRELVM v,SQBool b);
SQUIRREL_API void sq_pushuserpointer(HSQUIRRELVM v,SQUserPointer p);
SQUIRREL_API void sq_pushnull(HSQUIRRELVM v);
SQUIRREL_API void sq_pushthread(HSQUIRRELVM v, HSQUIRRELVM thread);
SQUIRREL_API SQObjectType sq_gettype(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_typeof(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQInteger sq_getsize(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQHash sq_gethash(HSQUIRRELVM v, SQInteger idx);
SQUIRREL_API SQRESULT sq_getbase(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQBool sq_instanceof(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_tostring(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API void sq_tobool(HSQUIRRELVM v, SQInteger idx, SQBool *b);
SQUIRREL_API SQRESULT sq_getstringandsize(HSQUIRRELVM v,SQInteger idx,const SQChar **c,SQInteger *size);
SQUIRREL_API SQRESULT sq_getstring(HSQUIRRELVM v,SQInteger idx,const SQChar **c);
SQUIRREL_API SQRESULT sq_getinteger(HSQUIRRELVM v,SQInteger idx,SQInteger *i);
SQUIRREL_API SQRESULT sq_getfloat(HSQUIRRELVM v,SQInteger idx,SQFloat *f);
SQUIRREL_API SQRESULT sq_getbool(HSQUIRRELVM v,SQInteger idx,SQBool *b);
SQUIRREL_API SQRESULT sq_getthread(HSQUIRRELVM v,SQInteger idx,HSQUIRRELVM *thread);
SQUIRREL_API SQRESULT sq_getuserpointer(HSQUIRRELVM v,SQInteger idx,SQUserPointer *p);
SQUIRREL_API SQRESULT sq_getuserdata(HSQUIRRELVM v,SQInteger idx,SQUserPointer *p,SQUserPointer *typetag);
SQUIRREL_API SQRESULT sq_settypetag(HSQUIRRELVM v,SQInteger idx,SQUserPointer typetag);
SQUIRREL_API SQRESULT sq_gettypetag(HSQUIRRELVM v,SQInteger idx,SQUserPointer *typetag);
SQUIRREL_API void sq_setreleasehook(HSQUIRRELVM v,SQInteger idx,SQRELEASEHOOK hook);
SQUIRREL_API SQRELEASEHOOK sq_getreleasehook(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQChar *sq_getscratchpad(HSQUIRRELVM v,SQInteger minsize);
SQUIRREL_API SQRESULT sq_getfunctioninfo(HSQUIRRELVM v,SQInteger level,SQFunctionInfo *fi);
SQUIRREL_API SQRESULT sq_getclosureinfo(HSQUIRRELVM v,SQInteger idx,SQInteger *nparams,SQInteger *nfreevars);
SQUIRREL_API SQRESULT sq_getclosurename(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_setnativeclosurename(HSQUIRRELVM v,SQInteger idx,const SQChar *name);
SQUIRREL_API SQRESULT sq_setinstanceup(HSQUIRRELVM v, SQInteger idx, SQUserPointer p);
SQUIRREL_API SQRESULT sq_getinstanceup(HSQUIRRELVM v, SQInteger idx, SQUserPointer *p,SQUserPointer typetag);
SQUIRREL_API SQRESULT sq_setclassudsize(HSQUIRRELVM v, SQInteger idx, SQInteger udsize);
SQUIRREL_API SQRESULT sq_newclass(HSQUIRRELVM v,SQBool hasbase);
SQUIRREL_API SQRESULT sq_createinstance(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_setattributes(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_getattributes(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_getclass(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API void sq_weakref(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_getdefaultdelegate(HSQUIRRELVM v,SQObjectType t);
SQUIRREL_API SQRESULT sq_getmemberhandle(HSQUIRRELVM v,SQInteger idx,HSQMEMBERHANDLE *handle);
SQUIRREL_API SQRESULT sq_getbyhandle(HSQUIRRELVM v,SQInteger idx,const HSQMEMBERHANDLE *handle);
SQUIRREL_API SQRESULT sq_setbyhandle(HSQUIRRELVM v,SQInteger idx,const HSQMEMBERHANDLE *handle);
/*object manipulation*/
SQUIRREL_API void sq_pushroottable(HSQUIRRELVM v);
SQUIRREL_API void sq_pushregistrytable(HSQUIRRELVM v);
SQUIRREL_API void sq_pushconsttable(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_setroottable(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_setconsttable(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_newslot(HSQUIRRELVM v, SQInteger idx, SQBool bstatic);
SQUIRREL_API SQRESULT sq_deleteslot(HSQUIRRELVM v,SQInteger idx,SQBool pushval);
SQUIRREL_API SQRESULT sq_set(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_get(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_rawget(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_rawset(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_rawdeleteslot(HSQUIRRELVM v,SQInteger idx,SQBool pushval);
SQUIRREL_API SQRESULT sq_newmember(HSQUIRRELVM v,SQInteger idx,SQBool bstatic);
SQUIRREL_API SQRESULT sq_rawnewmember(HSQUIRRELVM v,SQInteger idx,SQBool bstatic);
SQUIRREL_API SQRESULT sq_arrayappend(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_arraypop(HSQUIRRELVM v,SQInteger idx,SQBool pushval);
SQUIRREL_API SQRESULT sq_arrayresize(HSQUIRRELVM v,SQInteger idx,SQInteger newsize);
SQUIRREL_API SQRESULT sq_arrayreverse(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_arrayremove(HSQUIRRELVM v,SQInteger idx,SQInteger itemidx);
SQUIRREL_API SQRESULT sq_arrayinsert(HSQUIRRELVM v,SQInteger idx,SQInteger destpos);
SQUIRREL_API SQRESULT sq_setdelegate(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_getdelegate(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_clone(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_setfreevariable(HSQUIRRELVM v,SQInteger idx,SQUnsignedInteger nval);
SQUIRREL_API SQRESULT sq_next(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_getweakrefval(HSQUIRRELVM v,SQInteger idx);
SQUIRREL_API SQRESULT sq_clear(HSQUIRRELVM v,SQInteger idx);
/*calls*/
SQUIRREL_API SQRESULT sq_call(HSQUIRRELVM v,SQInteger params,SQBool retval,SQBool raiseerror);
SQUIRREL_API SQRESULT sq_resume(HSQUIRRELVM v,SQBool retval,SQBool raiseerror);
SQUIRREL_API const SQChar *sq_getlocal(HSQUIRRELVM v,SQUnsignedInteger level,SQUnsignedInteger idx);
SQUIRREL_API SQRESULT sq_getcallee(HSQUIRRELVM v);
SQUIRREL_API const SQChar *sq_getfreevariable(HSQUIRRELVM v,SQInteger idx,SQUnsignedInteger nval);
SQUIRREL_API SQRESULT sq_throwerror(HSQUIRRELVM v,const SQChar *err);
SQUIRREL_API SQRESULT sq_throwobject(HSQUIRRELVM v);
SQUIRREL_API void sq_reseterror(HSQUIRRELVM v);
SQUIRREL_API void sq_getlasterror(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_tailcall(HSQUIRRELVM v, SQInteger nparams);
/*raw object handling*/
SQUIRREL_API SQRESULT sq_getstackobj(HSQUIRRELVM v,SQInteger idx,HSQOBJECT *po);
SQUIRREL_API void sq_pushobject(HSQUIRRELVM v,HSQOBJECT obj);
SQUIRREL_API void sq_addref(HSQUIRRELVM v,HSQOBJECT *po);
SQUIRREL_API SQBool sq_release(HSQUIRRELVM v,HSQOBJECT *po);
SQUIRREL_API SQUnsignedInteger sq_getrefcount(HSQUIRRELVM v,HSQOBJECT *po);
SQUIRREL_API void sq_resetobject(HSQOBJECT *po);
SQUIRREL_API const SQChar *sq_objtostring(const HSQOBJECT *o);
SQUIRREL_API SQBool sq_objtobool(const HSQOBJECT *o);
SQUIRREL_API SQInteger sq_objtointeger(const HSQOBJECT *o);
SQUIRREL_API SQFloat sq_objtofloat(const HSQOBJECT *o);
SQUIRREL_API SQUserPointer sq_objtouserpointer(const HSQOBJECT *o);
SQUIRREL_API SQRESULT sq_getobjtypetag(const HSQOBJECT *o,SQUserPointer * typetag);
SQUIRREL_API SQUnsignedInteger sq_getvmrefcount(HSQUIRRELVM v, const HSQOBJECT *po);
/*GC*/
SQUIRREL_API SQInteger sq_collectgarbage(HSQUIRRELVM v);
SQUIRREL_API SQRESULT sq_resurrectunreachable(HSQUIRRELVM v);
/*serialization*/
SQUIRREL_API SQRESULT sq_writeclosure(HSQUIRRELVM vm,SQWRITEFUNC writef,SQUserPointer up);
SQUIRREL_API SQRESULT sq_readclosure(HSQUIRRELVM vm,SQREADFUNC readf,SQUserPointer up);
/*mem allocation*/
SQUIRREL_API void *sq_malloc(SQUnsignedInteger size);
SQUIRREL_API void *sq_realloc(void* p,SQUnsignedInteger oldsize,SQUnsignedInteger newsize);
SQUIRREL_API void sq_free(void *p,SQUnsignedInteger size);
/*debug*/
SQUIRREL_API SQRESULT sq_stackinfos(HSQUIRRELVM v,SQInteger level,SQStackInfos *si);
SQUIRREL_API void sq_setdebughook(HSQUIRRELVM v);
SQUIRREL_API void sq_setnativedebughook(HSQUIRRELVM v,SQDEBUGHOOK hook);
/*UTILITY MACRO*/
#define sq_isnumeric(o) ((o)._type&SQOBJECT_NUMERIC)
#define sq_istable(o) ((o)._type==OT_TABLE)
#define sq_isarray(o) ((o)._type==OT_ARRAY)
#define sq_isfunction(o) ((o)._type==OT_FUNCPROTO)
#define sq_isclosure(o) ((o)._type==OT_CLOSURE)
#define sq_isgenerator(o) ((o)._type==OT_GENERATOR)
#define sq_isnativeclosure(o) ((o)._type==OT_NATIVECLOSURE)
#define sq_isstring(o) ((o)._type==OT_STRING)
#define sq_isinteger(o) ((o)._type==OT_INTEGER)
#define sq_isfloat(o) ((o)._type==OT_FLOAT)
#define sq_isuserpointer(o) ((o)._type==OT_USERPOINTER)
#define sq_isuserdata(o) ((o)._type==OT_USERDATA)
#define sq_isthread(o) ((o)._type==OT_THREAD)
#define sq_isnull(o) ((o)._type==OT_NULL)
#define sq_isclass(o) ((o)._type==OT_CLASS)
#define sq_isinstance(o) ((o)._type==OT_INSTANCE)
#define sq_isbool(o) ((o)._type==OT_BOOL)
#define sq_isweakref(o) ((o)._type==OT_WEAKREF)
#define sq_type(o) ((o)._type)
/* deprecated */
#define sq_createslot(v,n) sq_newslot(v,n,SQFalse)
#define SQ_OK (0)
#define SQ_ERROR (-1)
#define SQ_FAILED(res) (res<0)
#define SQ_SUCCEEDED(res) (res>=0)
#ifdef __GNUC__
# define SQ_UNUSED_ARG(x) x __attribute__((__unused__))
#else
# define SQ_UNUSED_ARG(x) x
#endif
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*_SQUIRREL_H_*/

View File

@ -0,0 +1,23 @@
/*
*
* Original Javascript version by David Hedbor(http://www.bagley.org/~doug/shootout/)
*
*/
function Ack(M, N) {
if (M == 0) return( N + 1 );
if (N == 0) return( Ack(M - 1, 1) );
return( Ack(M - 1, Ack(M, (N - 1))) );
}
local n;
if(vargv.len()!=0) {
n = vargv[0].tointeger();
if(n < 1) n = 1;
} else {
n = 1;
}
print("n="+n+"\n");
print("Ack(3,"+ n+ "):"+ Ack(3, n));

View File

@ -0,0 +1,29 @@
/*
*
* Original Javascript version by David Hedbor(http://www.bagley.org/~doug/shootout/)
*
*/
local n, i, k;
if(vargv.len()!=0) {
n = vargv[0].tointeger();
if(n < 1) n = 1;
} else {
n = 1;
}
local x = []; x.resize(n);
local y = []; y.resize(n);
for (i = 0; i < n; i+=1) {
x[i] = i + 1;
y[i] = 0;
}
for (k = 0 ; k < n; k+=1) {
for (i = n-1; i >= 0; i-=1) {
y[i] = y[i]+ x[i];
}
}
print(y[0].tostring()+" "+y[n-1]);

View File

@ -0,0 +1,49 @@
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
class BaseVector {
constructor(...)
{
if(vargv.len() >= 3) {
x = vargv[0];
y = vargv[1];
z = vargv[2];
}
}
x = 0;
y = 0;
z = 0;
}
class Vector3 extends BaseVector {
function _add(other)
{
if(other instanceof this.getclass())
return ::Vector3(x+other.x,y+other.y,z+other.z);
else
throw "wrong parameter";
}
function Print()
{
::print(x+","+y+","+z+"\n");
}
}
local v0 = Vector3(1,2,3)
local v1 = Vector3(11,12,13)
local v2 = v0 + v1;
v2.Print();
FakeNamespace <- {
Utils = {}
}
class FakeNamespace.Utils.SuperClass {
constructor()
{
::print("FakeNamespace.Utils.SuperClass")
}
}
local testy = FakeNamespace.Utils.SuperClass();

View File

@ -0,0 +1,35 @@
class Foo {
//constructor
constructor(a)
{
testy = ["stuff",1,2,3];
}
//attributes of PrintTesty
</ test = "freakin attribute"/>
function PrintTesty()
{
foreach(i,val in testy)
{
::print("idx = "+i+" = "+val+" \n");
}
}
//attributes of testy
</ flippy = 10 , second = [1,2,3] />
testy = null;
}
foreach(member,val in Foo)
{
::print(member+"\n");
local attr;
if((attr = Foo.getattributes(member)) != null) {
foreach(i,v in attr)
{
::print("\t"+i+" = "+(typeof v)+"\n");
}
}
else {
::print("\t<no attributes>\n")
}
}

View File

@ -0,0 +1,25 @@
function coroutine_test(a,b)
{
::print(a+" "+b+"\n");
local ret = ::suspend("suspend 1");
::print("the coroutine says "+ret+"\n");
ret = ::suspend("suspend 2");
::print("the coroutine says "+ret+"\n");
ret = ::suspend("suspend 3");
::print("the coroutine says "+ret+"\n");
return "I'm done"
}
local coro = ::newthread(coroutine_test);
local susparam = coro.call("test","coroutine"); //starts the coroutine
local i = 1;
do
{
::print("suspend passed ["+susparam+"]\n")
susparam = coro.wakeup("ciao "+i);
++i;
}while(coro.getstatus()=="suspended")
::print("return passed ["+susparam+"]\n")

View File

@ -0,0 +1,54 @@
PEntity <- {
name="noname"
pos={x=0,y=0,z=0}
type="entity"
//methamethod
_typeof=function()
{
return type;
}
}
function PEntity::PrintPos()
{
::print("x="+pos.x+" y="+pos.y+" z="+pos.z+"\n");
}
function PEntity::new(name,pos)
{
local newentity=clone ::PEntity;
if(name)
newentity.name=name;
if(pos)
newentity.pos=pos;
return newentity;
}
PPlayer <- {
model="warrior.mdl"
weapon="fist"
health=100
armor=0
//overrides the parent type
type="player"
}
function PPlayer::new(name,pos)
{
local p = clone ::PPlayer;
local newplayer = ::PEntity.new(name,pos);
newplayer.setdelegate(p);
return newplayer;
}
local player=PPlayer.new("godzilla",{x=10,y=20,z=30});
::print("PLAYER NAME"+player.name+"\n");
::print("ENTITY TYPE"+typeof player+"\n");
player.PrintPos();
player.pos.x=123;
player.PrintPos();

View File

@ -0,0 +1,15 @@
/*
*
* Original Javascript version by David Hedbor(http://www.bagley.org/~doug/shootout/)
*
*/
function fib(n)
{
if (n < 2) return 1
return fib(n-2) + fib(n-1)
}
local n = vargv.len()!=0?vargv[0].tointeger():1
print(fib(n)+"\n")

View File

@ -0,0 +1,33 @@
function min(x,y)
return x<y?x:y;
function max(x,y)
return x>y?x:y;
if(min(100,200)>max(50,20))
print("I'm useless statement just to show up the if/else\n");
else
print("squirrel!!\n");
print("\n")
function typy(obj)
{
switch(typeof obj)
{
case "integer":
case "float":
return "is a number";
case "table":
case "array":
return "is a container";
default:
return "is other stuff"
}
}
local a=1,b={},c=function(a,b){return a+b;}
print("a "+typy(a)+"\n");
print("b "+typy(b)+"\n");
print("c "+typy(c)+"\n");

View File

@ -0,0 +1,42 @@
/*
*Random number function from The Great Computer Language shootout
*converted to a generator func
*/
function gen_random(max) {
local last=42
local IM = 139968;
local IA = 3877;
local IC = 29573;
for(;;){ //loops forever
yield (max * (last = (last * IA + IC) % IM) / IM);
}
}
local randtor=gen_random(100);
print("RAND NUMBERS \n")
for(local i=0;i<10;i+=1)
print(">"+resume randtor+"\n");
print("FIBONACCI \n")
function fiboz(n)
{
local prev=0;
local curr=1;
yield 1;
for(local i=0;i<n-1;i+=1)
{
local res=prev+curr;
prev=curr;
yield curr=res;
}
return prev+curr;
}
foreach(val in fiboz(10))
{
::print(">"+val+"\n");
}

View File

@ -0,0 +1 @@
print("Hello World!")

View File

@ -0,0 +1,40 @@
/*translation of the list test from The Great Computer Language Shootout
*/
function compare_arr(a1,a2)
{
foreach(i,val in a1)
if(val!=a2[i])return null;
return 1;
}
function test()
{
local size=10000
local l1=[]; l1.resize(size);
for(local i=0;i<size;i+=1) l1[i]=i;
local l2=clone l1;
local l3=[]
l2.reverse();
while(l2.len()>0)
l3.append(l2.pop());
while(l3.len()>0)
l2.append(l3.pop());
l1.reverse();
if(compare_arr(l1,l2))
return l1.len();
return null;
}
local n = vargv.len()!=0?vargv[0].tointeger():1
for(local i=0;i<n;i+=1)
if(!test())
{
print("failed");
return;
}
print("oki doki");

View File

@ -0,0 +1,32 @@
local arr=["one","two","three"]
::print("FOREACH\n");
foreach(i,val in arr)
{
::print("index ["+i+"]="+val+"\n");
}
::print("FOR\n");
for(local i=0;i<arr.len();i+=1)
{
::print("index ["+i+"]="+arr[i]+"\n");
}
::print("WHILE\n");
local i=0;
while(i<arr.len())
{
::print("index ["+i+"]="+arr[i]+"\n");
i+=1;
}
::print("DO WHILE\n");
local i=0;
do
{
::print("index ["+i+"]="+arr[i]+"\n");
i+=1;
}while(i<arr.len());

View File

@ -0,0 +1,44 @@
/*
*
* Original Javascript version by David Hedbor(http://www.bagley.org/~doug/shootout/)
*
*/
local SIZE=30;
function mkmatrix(rows, cols) {
local i, j, count = 1;
local m = []; m.resize(rows);
for (i = 0; i < rows; i+=1) {
m[i] = [];m[i].resize(cols)
for (j = 0; j < cols; j+=1) {
m[i][j] = count+=1;
}
}
return m;
}
function mmult(rows, cols, m1, m2, m3) {
local i, j, k, val;
for (i = 0; i < rows; i+=1) {
for (j = 0; j < cols; j+=1) {
val = 0;
for (k = 0; k < cols; k+=1) {
val += m1[i][k] * m2[k][j];
}
m3[i][j] = val;
}
}
return m3;
}
local n = vargv.len()!=0?vargv[0].tointeger():1
local m1 = mkmatrix(SIZE, SIZE);
local m2 = mkmatrix(SIZE, SIZE);
local mm = mkmatrix(SIZE, SIZE);
for (local i = 0; i < n; i+=1) {
mmult(SIZE, SIZE, m1, m2, mm);
}
print(mm[0][0]+" "+mm[2][3]+" "+mm[3][2]+" "+mm[4][4]);

View File

@ -0,0 +1,115 @@
local base_vec={
function _add(n)
{
return {
x=x+n.x,
y=y+n.y,
z=z+n.z,
}
}
function _sub(n)
{
return {
x=x-n.x,
y=y-n.y,
z=z-n.z,
}
}
function _div(n)
{
return {
x=x/n.x,
y=y/n.y,
z=z/n.z,
}
}
function _mul(n)
{
return {
x=x*n.x,
y=y*n.y,
z=z*n.z,
}
}
function _modulo(n)
{
return {
x=x%n,
y=y%n,
z=z%n,
}
}
function _typeof() {return "vector";}
function _get(key)
{
if(key==100)
{
return test_field;
}
},
function _set(key,val)
{
::print("key = "+key+"\n");
::print("val = "+val+"\n")
if(key==100)
{
return test_field=val;
}
}
test_field="nothing"
}
function vector(_x,_y,_z)
{
return {x=_x,y=_y,z=_z }.setdelegate(base_vec);
}
////////////////////////////////////////////////////////////
local v1=vector(1.5,2.5,3.5);
local v2=vector(1.5,2.5,3.5);
local r=v1+v2;
foreach(i,val in r)
{
print(i+" = "+val+"\n");
}
r=v1*v2;
foreach(i,val in r)
{
print(i+" = "+val+"\n");
}
r=v1/v2;
foreach(i,val in r)
{
print(i+" = "+val+"\n");
}
r=v1-v2;
foreach(i,val in r)
{
print(i+" = "+val+"\n");
}
r=v1%2;
foreach(i,val in r)
{
print(i+" = "+val+"\n");
}
print(v1[100]+"\n");
v1[100]="set SUCCEEDED";
print(v1[100]+"\n");
if(typeof v1=="vector")
print("<SUCCEEDED>\n");
else
print("<FAILED>\n");

Some files were not shown because too many files have changed in this diff Show More