Arrays
JFuncMachine provides expressions to get and set values in an array and also to create new arrays.
Creating New Arrays
The NewArray expression takes an array element type and
an expression indicating the desired array size, and allocates
a new array.
The following method takes an array size as a parameter and returns an array of bytes corresponding to the size:
MethodDef method = new MethodDef("arraytest", Access.PUBLIC, new Field[] {
new Field("n", SimpleTypes.INT)},
new ArrayType(SimpleTypes.BYTE),
new NewArray(SimpleTypes.BYTE, new GetValue("n", SimpleTypes.INT)));The NewArrayWithValues expression takes an array element type
and an array of expressions and creates an array whose elements
are the values of the expressions passed in. The size is given
by the number of expressions. The following example method
takes three int parameters and creates an int array containing
those three values:
MethodDef method = new MethodDef("arraytest", Access.PUBLIC, new Field[] {
new Field("v1", SimpleTypes.INT),
new Field("v2", SimpleTypes.INT),
new Field("v3", SimpleTypes.INT),
},
new ArrayType(SimpleTypes.INT),
new NewArrayWithValues(SimpleTypes.INT,
new Expression[] {
new GetValue("v1", SimpleTypes.INT),
new GetValue("v2", SimpleTypes.INT),
new GetValue("v3", SimpleTypes.INT)
}));Getting and Setting Array Values
The ArrayGet expression takes an array expression and an index
expression, and returns the value in the array at that index position.
The following example function takes an array arr of bytes and an
int index i as parameters, and returns arr[i]:
MethodDef method = new MethodDef("arraytest", Access.PUBLIC, new Field[] {
new Field("arr", new ArrayType(SimpleTypes.BYTE)),
new Field("i", SimpleTypes.INT)},
SimpleTypes.BYTE,
new ArrayGet(new GetValue("arr", new ArrayType(SimpleTypes.BYTE)),
new GetValue("i", SimpleTypes.INT)));Similarly, the ArraySet expression takes an array expression,
and index expression, and a value expression, and stores the
value at the index position in the array. The following method
definition takes an array arr of string, an index i, and a string
value x, and stores x in arr[i]:
MethodDef method = new MethodDef("arraytest", Access.PUBLIC, new Field[] {
new Field("arr", new ArrayType(SimpleTypes.STRING)),
new Field("i", SimpleTypes.INT),
new Field( "x", SimpleTypes.STRING)},
SimpleTypes.UNIT,
new ArraySet(new GetValue("arr", new ArrayType(SimpleTypes.STRING)),
new GetValue("i", SimpleTypes.INT),
new GetValue("x", SimpleTypes.STRING)))