-
-
Notifications
You must be signed in to change notification settings - Fork 131
id Advanced microScript
microScript 2.0 introduces the Object, List, String, Number and Function prototypes. Such prototypes are collections of functions that you can define and then use on values of their corresponding types.
Example: we will create a function which, when applied to a string, returns the same string with the first letter capitalized:
String.capitalized = function()
if this.length > 0 then
this[0].toUpperCase() + this.substring(1)
else
""
end
endNote that in the course of the defined function,
thisrefers to the string instance which the function is called on.
We can then use the function on any string value like this:
lastname = "doe".capitalized()
firstname = "john"
firstname = firstname.capitalized()
city = "paris"
print( firstname + " " + lastname + " " + city.capitalized() )Note that string values are always constants. Any function that looks like transforming a string does not change the original string value, it just returns a new string value holding the transformed string.
Another example:
List.modulo = function(mod)
local result = []
for i=0 to this.length-1 by mod
result += this[i]
end
result
endOnce this is defined, you can call the function modulo on lists, which will return a subset of the elements in the list:
[1,2,3,4,5,6,7,8].modulo(2)
[1,3,5,7]When creating classes, you can define how the microScript operators + - * / % | & should be applied to object instances of your class.
Vector3 = class
constructor = function(x,y,z)
this.x = x
this.y = y
this.z = z
end
"+" = function(a,b)
new Vector3( a.x+b.x, a.y+b.y, a.z+b.z )
end
endWhen you define such a binary operator ("binary" meaning two arguments here) like + , think that it will be used this way: a + b. a and b will be the two arguments to your overloading function.
Note: when
a <op> bis encountered in the code andais not a number, the operation to carry out is decided depending on the type or class ofa. Ifais a List and<op>is defined in the List prototype, then that will be the operation carried out. Ifais an instance of a classVector3and the class defines<op>then that will be the operation carried out.
special case: when an occurence of
-bis found in the code ; if the prototype or parent class ofbis found to define the binary operator-, then the function ( a, b ) is called withaset to0andbset to the value ofb. Thus you can implement the-operator for your Vector3 class this way:
Vector3."-" = function( a, b )
if a then
new Vector3( a.x-b.x, a.y-b.y, a.z-b.z )
else
new Vector3( -b.x, -b.y, -b.z )
end
endYou can also overload operators for the core types of microStudio. Example:
String."*" = function(a,b)
local result = a
for i = 2 to b by 1
result += a
end
result
endUse:
"abc" * 5
"abcabcabcabcabc"Note: Overloading binary operators
+ - * / % | &for the Number prototype is not supported!