Skip to content

Architecture of JavaScript variables

Neil Kolban edited this page Oct 8, 2015 · 13 revisions

The management of JavaScript variables within Espruino is possibly one of the most important areas of the projects.

The code maintaining the JavaScript variables can be found within src\jsvar.c. Within there you will find a wealth of functions for working with variables.

####JsVar When programming within the internals of Espruino, we will find that a JavaScript variable is represented by a data structure called a JsVar. This is the internal representation of the variable.

####Construction The variables have constructors for working with them. For example, jsvNewFromString will create a new string variable.

We can also create a new object using jspNewObject() or from jsvNewWithFlags(JSV_OBJECT). We can set properties on the object using jsvObjectSetChild().

To create an array we use jsvNewWithFlags(JSV_ARRAY).

####Content access Since a JsVar is a "container" for data, we may wish to access the content of those variables. We can do so using accessor functions such as jsvGetInteger.

If we are passed a JsVar instance, we often want to know what kind of variable the object represents. We can determine that with one of the jsvIs<type> methods.

####References and Locks Part of the concept of variables are references and locks. References are the number of references to the variable from other JavaScript variables. Locks are the number of references from native code. This comes into play when we consider garbage collection. A variable can possibly be freed if it has > 0 references but it can never be freed if it has > 0 locks.

Q - Kolban 2015-10-05: When a variable is created, is it locked?

####Invoking functions passed as variables Consider the notion of a JsVar that represents a function. How can we invoke that function from within our C code? The answer is to use the jsiQueueEvents() call. Here is an example invoking the function referenced by the JsVar variable called jsGotIpCallback which takes two parameters:

JsVar *params[2];
params[0] = jsvNewFromInteger(eventType);
params[1] = details;
jsiQueueEvents(NULL, jsGotIpCallback, params, 2);

#Key Functions by category ##Strings

  • jsvAppendStringVar
  • jsvAppendStringVarComplete
  • jsvAsString
  • jsvCompareString
  • jsvGetConstString
  • jsvGetString
  • jsvGetStringIndexOf
  • jsvGetStringLength
  • jsvGetCharInString
  • jsvNewFromStringVar
  • jsvNewFromString - Create a JsVar from a string.
  • jsvNewStringOfLength
  • jsvIsEmptyString
  • jsvIsString
  • jsvIsStringNumericInt
  • jsvIsStringNumericStrict
  • jsvIsStringEqualOtStartsWith
  • jsvIsStringEqual
  • jsvIsStringEqualAndUnlock
  • jsvSetString
  • jsvStringTrimRight
Clone this wiki locally