classes.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. .. _classes:
  2. =================
  3. Classes
  4. =================
  5. .. index::
  6. single: Classes
  7. Squirrel implements a class mechanism similar to languages like Java/C++/etc...
  8. however because of its dynamic nature it differs in several aspects.
  9. Classes are first class objects like integer or strings and can be stored in
  10. table slots local variables, arrays and passed as function parameters.
  11. -----------------
  12. Class Declaration
  13. -----------------
  14. .. index::
  15. pair: declaration; Class
  16. single: Class Declaration
  17. A class object is created through the keyword 'class' . The class object follows
  18. the same declaration syntax of a table(see :ref:`Tables <tables>`) with the only difference
  19. of using ';' as optional separator rather than ','.
  20. For instance: ::
  21. class Foo {
  22. //constructor
  23. constructor(a)
  24. {
  25. testy = ["stuff",1,2,3,a];
  26. }
  27. //member function
  28. function PrintTesty()
  29. {
  30. foreach(i,val in testy)
  31. {
  32. ::print("idx = "+i+" = "+val+" \n");
  33. }
  34. }
  35. //property
  36. testy = null;
  37. }
  38. the previous code example is a syntactic sugar for: ::
  39. Foo <- class {
  40. //constructor
  41. constructor(a)
  42. {
  43. testy = ["stuff",1,2,3,a];
  44. }
  45. //member function
  46. function PrintTesty()
  47. {
  48. foreach(i,val in testy)
  49. {
  50. ::print("idx = "+i+" = "+val+" \n");
  51. }
  52. }
  53. //property
  54. testy = null;
  55. }
  56. in order to emulate namespaces, it is also possible to declare something like this::
  57. //just 2 regular nested tables
  58. FakeNamespace <- {
  59. Utils = {}
  60. }
  61. class FakeNamespace.Utils.SuperClass {
  62. constructor()
  63. {
  64. ::print("FakeNamespace.Utils.SuperClass")
  65. }
  66. function DoSomething()
  67. {
  68. ::print("DoSomething()")
  69. }
  70. }
  71. function FakeNamespace::Utils::SuperClass::DoSomethingElse()
  72. {
  73. ::print("FakeNamespace::Utils::SuperClass::DoSomethingElse()")
  74. }
  75. local testy = FakeNamespace.Utils.SuperClass();
  76. testy.DoSomething();
  77. testy.DoSomethingElse();
  78. After its declaration, methods or properties can be added or modified by following
  79. the same rules that apply to a table(operator ``<-``).::
  80. //adds a new property
  81. Foo.stuff <- 10;
  82. //modifies the default value of an existing property
  83. Foo.testy <- "I'm a string";
  84. //adds a new method
  85. function Foo::DoSomething(a,b)
  86. {
  87. return a+b;
  88. }
  89. After a class is instantiated is no longer possible to add new properties however is possible to add or replace methods.
  90. ^^^^^^^^^^^^^^^^
  91. Static variables
  92. ^^^^^^^^^^^^^^^^
  93. .. index::
  94. pair: static variables; Class
  95. single: Static variables
  96. Squirrel's classes support static member variables. A static variable shares its value
  97. between all instances of the class. Statics are declared by prefixing the variable declaration
  98. with the keyword ``static``; the declaration must be in the class body.
  99. .. note:: Statics are read-only.
  100. ::
  101. class Foo {
  102. constructor()
  103. {
  104. //..stuff
  105. }
  106. name = "normal variable";
  107. //static variable
  108. static classname = "The class name is foo";
  109. };
  110. ^^^^^^^^^^^^^^^^
  111. Class Attributes
  112. ^^^^^^^^^^^^^^^^
  113. .. index::
  114. pair: attributes; Class
  115. single: Class Attributes
  116. Classes allow to associate attributes to it's members. Attributes are a form of metadata
  117. that can be used to store application specific informations, like documentations
  118. strings, properties for IDEs, code generators etc...
  119. Class attributes are declared in the class body by preceding the member declaration and
  120. are delimited by the symbol ``</`` and ``/>``.
  121. Here an example: ::
  122. class Foo </ test = "I'm a class level attribute" />{
  123. </ test = "freakin attribute" /> //attributes of PrintTesty
  124. function PrintTesty()
  125. {
  126. foreach(i,val in testy)
  127. {
  128. ::print("idx = "+i+" = "+val+" \n");
  129. }
  130. }
  131. </ flippy = 10 , second = [1,2,3] /> //attributes of testy
  132. testy = null;
  133. }
  134. Attributes are, matter of fact, a table. Squirrel uses ``</ />`` syntax
  135. instead of curly brackets ``{}`` for the attribute declaration to increase readability.
  136. This means that all rules that apply to tables apply to attributes.
  137. Attributes can be retrieved through the built-in function ``classobj.getattributes(membername)`` (see <link linkend="builtin">built-in functions</link>).
  138. and can be modified/added through the built-in function ``classobj.setattributes(membername,val)``.
  139. the following code iterates through the attributes of all Foo members.::
  140. foreach(member,val in Foo)
  141. {
  142. ::print(member+"\n");
  143. local attr;
  144. if((attr = Foo.getattributes(member)) != null) {
  145. foreach(i,v in attr)
  146. {
  147. ::print("\t"+i+" = "+(typeof v)+"\n");
  148. }
  149. }
  150. else {
  151. ::print("\t<no attributes>\n")
  152. }
  153. }
  154. -----------------
  155. Class Instances
  156. -----------------
  157. .. index::
  158. pair: instances; Class
  159. single: Class Instances
  160. The class objects inherits several of the table's feature with the difference that multiple instances of the
  161. same class can be created.
  162. A class instance is an object that share the same structure of the table that created it but
  163. holds is own values.
  164. Class *instantiation* uses function notation.
  165. A class instance is created by calling a class object. Can be useful to imagine a class like a function
  166. that returns a class instance.::
  167. //creates a new instance of Foo
  168. local inst = Foo();
  169. When a class instance is created its member are initialized *with the same value* specified in the
  170. class declaration. The values are copied verbatim, *no cloning is performed* even if the value is a container or a class instances.
  171. .. note:: FOR C# and Java programmers:
  172. Squirrel doesn't clone member's default values nor executes the member declaration for each instance(as C# or java).
  173. So consider this example: ::
  174. class Foo {
  175. myarray = [1,2,3]
  176. mytable = {}
  177. }
  178. local a = Foo();
  179. local b = Foo();
  180. In the snippet above both instances will refer to the same array and same table.To achieve what a C# or Java programmer would
  181. expect, the following approach should be taken. ::
  182. class Foo {
  183. myarray = null
  184. mytable = null
  185. constructor()
  186. {
  187. myarray = [1,2,3]
  188. mytable = {}
  189. }
  190. }
  191. local a = Foo();
  192. local b = Foo();
  193. When a class defines a method called 'constructor', the class instantiation operation will
  194. automatically invoke it for the newly created instance.
  195. The constructor method can have parameters, this will impact on the number of parameters
  196. that the *instantiation operation* will require.
  197. Constructors, as normal functions, can have variable number of parameters (using the parameter ``...``).::
  198. class Rect {
  199. constructor(w,h)
  200. {
  201. width = w;
  202. height = h;
  203. }
  204. x = 0;
  205. y = 0;
  206. width = null;
  207. height = null;
  208. }
  209. //Rect's constructor has 2 parameters so the class has to be 'called'
  210. //with 2 parameters
  211. local rc = Rect(100,100);
  212. After an instance is created, its properties can be set or fetched following the
  213. same rules that apply to tables. Methods cannot be set.
  214. Instance members cannot be removed.
  215. The class object that created a certain instance can be retrieved through the built-in function
  216. ``instance.getclass()`` (see :ref:`built-in functions <builtin_functions>`)
  217. The operator ``instanceof`` tests if a class instance is an instance of a certain class.::
  218. local rc = Rect(100,100);
  219. if(rc instanceof ::Rect) {
  220. ::print("It's a rect");
  221. }
  222. else {
  223. ::print("It isn't a rect");
  224. }
  225. .. note:: Since Squirrel 3.x instanceof doesn't throw an exception if the left expression is not a class, it simply fails
  226. --------------
  227. Inheritance
  228. --------------
  229. .. index::
  230. pair: inheritance; Class
  231. single: Inheritance
  232. Squirrel's classes support single inheritance by adding the keyword ``extends``, followed
  233. by an expression, in the class declaration.
  234. The syntax for a derived class is the following: ::
  235. class SuperFoo extends Foo {
  236. function DoSomething() {
  237. ::print("I'm doing something");
  238. }
  239. }
  240. When a derived class is declared, Squirrel first copies all base's members in the
  241. new class then proceeds with evaluating the rest of the declaration.
  242. A derived class inherit all members and properties of it's base, if the derived class
  243. overrides a base function the base implementation is shadowed.
  244. It's possible to access a overridden method of the base class by fetching the method from
  245. through the 'base' keyword.
  246. Here an example: ::
  247. class Foo {
  248. function DoSomething() {
  249. ::print("I'm the base");
  250. }
  251. };
  252. class SuperFoo extends Foo {
  253. //overridden method
  254. function DoSomething() {
  255. //calls the base method
  256. base.DoSomething();
  257. ::print("I'm doing something");
  258. }
  259. }
  260. Same rule apply to the constructor. The constructor is a regular function (apart from being automatically invoked on construction).::
  261. class BaseClass {
  262. constructor()
  263. {
  264. ::print("Base constructor\n");
  265. }
  266. }
  267. class ChildClass extends BaseClass {
  268. constructor()
  269. {
  270. base.constructor();
  271. ::print("Child constructor\n");
  272. }
  273. }
  274. local test = ChildClass();
  275. The base class of a derived class can be retrieved through the built-in method ``getbase()``.::
  276. local thebaseclass = SuperFoo.getbase();
  277. Note that because methods do not have special protection policies when calling methods of the same
  278. 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.
  279. 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() ).::
  280. class Foo {
  281. function DoSomething() {
  282. ::print("I'm the base");
  283. }
  284. function DoIt()
  285. {
  286. DoSomething();
  287. }
  288. };
  289. class SuperFoo extends Foo {
  290. //overridden method
  291. function DoSomething() {
  292. ::print("I'm the derived");
  293. }
  294. function DoIt() {
  295. base.DoIt();
  296. }
  297. }
  298. //creates a new instance of SuperFoo
  299. local inst = SuperFoo();
  300. //prints "I'm the derived"
  301. inst.DoIt();
  302. ----------------------
  303. Metamethods
  304. ----------------------
  305. .. index::
  306. pair: metamethods; Class
  307. single: Class metamethods
  308. Class instances allow the customization of certain aspects of the
  309. their semantics through metamethods(see see :ref:`Metamethods <metamethods>`).
  310. For C++ programmers: "metamethods behave roughly like overloaded operators".
  311. The metamethods supported by classes are ``_add, _sub, _mul, _div, _unm, _modulo,
  312. _set, _get, _typeof, _nexti, _cmp, _call, _delslot, _tostring``
  313. Class objects instead support only 2 metamethods : ``_newmember`` and ``_inherited``
  314. the following example show how to create a class that implements the metamethod ``_add``.::
  315. class Vector3 {
  316. constructor(...)
  317. {
  318. if(vargv.len() >= 3) {
  319. x = vargv[0];
  320. y = vargv[1];
  321. z = vargv[2];
  322. }
  323. }
  324. function _add(other)
  325. {
  326. return ::Vector3(x+other.x,y+other.y,z+other.z);
  327. }
  328. x = 0;
  329. y = 0;
  330. z = 0;
  331. }
  332. local v0 = Vector3(1,2,3)
  333. local v1 = Vector3(11,12,13)
  334. local v2 = v0 + v1;
  335. ::print(v2.x+","+v2.y+","+v2.z+"\n");
  336. Since version 2.1, classes support 2 metamethods ``_inherited`` and ``_newmember``.
  337. ``_inherited`` is invoked when a class inherits from the one that implements ``_inherited``.
  338. ``_newmember`` is invoked for each member that is added to the class(at declaration time).