ChaiScript Tutorial (4) – Functions in ChaiScript

We have discussed be basic syntax of ChaiScript in the previous tutorial. Today, I’m going to talk about functions in ChaiScript.

Define a function in ChaiScript

We can define a function in ChaiScript. Here is how its done. The general syntax is

def func(x)
{
	//function body here
}

It is just like how a function is defined any language(that is not functional). Just like it is

For example. A function that gives you the answer to the the answer to life the universe and everything can be written as

def getAnswerOfEverything()
{
	return 42;
}

Returning value from a function

Surly you can return value from ChaiScript. It is also done by the keyword  return. However, unlike C/C++. A function isn’t limited to returning a single type of value. (Ex: a function int foo(int x) have to return an integer value).

Thus the following function is valid in ChaiScript.

def foo(num)
{
	if(num%2 == 0)
		return "Odd"
	return False
} 

Assigning a function to a variable

A ChaiScript function in the interpolator std::function. Thus you can assign a ChaiScript function  to a variable(which makes the variable that is a function) or get a std::function in C++ that calls the ChaiScript Function. We will talk about calling ChaiScirpt functions later. I’m going to demonstrate how to assigning a ChaiScript function to a variable, then call it. I’s easy

def f()
{
	return 42
}
var func = f

//call it
print(func())

That’s it. Simple!

This ends this short tutorial. We will be talking about calling ChaiScript functions from C++ in the next tutorial. It is available here.

 

 

One thought on “ChaiScript Tutorial (4) – Functions in ChaiScript

Add yours

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Website Powered by WordPress.com.

Up ↑