Appearance
Functions
You can define functions by using function keyword in an assignment statement.
gs
myFunction = function
return 1337
end function
print myFunction //print 1337
In this snippet, you can see that a function gets declared and assigned to a variable called myFunction. The function is then invoked and returns the value 1337..
Parameters
Parameters can be defined as well. Parameters are comma-separated and can be set to a default value.
gs
myFunction = function(myText = "world")
return "hello " + myText
end function
print myFunction //prints "hello world"
print myFunction("bill") //prints "hello bill"
Invokation
Every function will get invoked by default, regardless if parentheses got provided or not. Invokation can be prevented by using an @ operator in front of the identifier. This can be useful if you want to pass your function as a parameter or assign it to a different variable.
gs
myOtherPrint = @print
myOtherPrint("hello world") //prints "hello world"
Self
By using the identifier self as a parameter you'll also be able to get the current call context. This can be useful when creating functions that can be used for different kinds of classes.
gs
getKey = function(self, key)
if self.hasIndex(key) then return self[key]
return null
end function
myObject = {
"foo": 42,
"getKey": @getKey,
}
print(getKey(myObject, "foo")) //prints 42
print(myObject.getKey("foo")) //prints 42
Scopes
Each function block will have an independent scope. Through using variables such as globals and outer other scopes can be accessed. So in case you got nested functions you could use the outer variable to access the parent scope.
gs
counterFactory = function
locals.count = 0
incVariable = function
outer.count += 1
return outer.count
end function
return @incVariable
end function
counter = counterFactory
print(counter) //prints 1
print(counter) //prints 2
print(counter) //prints 3
Each print will output a number that is increasing by one.
Signature
To get the signature of a function you need to cast it to a string. The function body will not be included.
gs
getKey = function(self, key)
if self.hasIndex(key) then return self[key]
return null
end function
print("" + @getKey) //prints "FUNCTION(self, key)"
The output can be useful if you for example want to inspect the functions of an imported library.
gs
myFunction = function(value, default = "test")
return value + default
end function
getFunctionParameterAsList = function(fn)
signature = "" + @fn
return signature[9:-1].split("(?<=[^,\)]+),")
end function
print(getFunctionParameterAsList(@myFunction)) //prints ["value", "default"]