Understanding The Stack
Last changed: -


One of the most important concepts to understand in order to embed squirrel,is 'the virtual machine stack'.

The majority of Squirrel's API functions exchanges values with C/C++ through a stack of squirrel objects.

Squirrel objects are strings, integers, floats, tables, arrays etc...

To better understand take a look at the following code C

        sq_pushfloat(v,1.5f); //pushes a float
        sq_pushroottable(v); //pushes the root table
        sq_pushstring(v,"I'm a string",-1); //pushed a string

and immagine that the result in Squirrel's stack would be something like this table

positive index negative index object
3(top) -1 "I'm a string"
2 -2 root table
1 -3 1.5

Using the stack

After a virtual machine is created(calling *sq_open()) the stack is empty.

positive index negative index object

let's assume we want to create a global variable called test and set its value to 123(integer). This is done through the API function sq_createslot.

from the reference manual sq_createslot: pops a key and a value from the stack and performs a set operation on the table or class that is at position idx in the stack, if the slot does not exits it will be created.


this is the equivalent of the following squirrel code

        test <- 123;

step by step

given an empty stack

positive index negative index object

pushes the root table that is the target object where we want to create the new slot

positive index negative index object
1 -1 root table

pushes the name of the slot we want to create

positive index negative index object
2 -1 "test"
1 -2 root table

pushes the value of the slot we want to create

positive index negative index object
3 -1 123
2 -2 "test"
1 -3 root table

pops the value and the key and sets the object at position -3 (from the top of the stack) that is the root table we pushed.

positive index agen index object
1 -1 root table

as you can notice in the tabular representation of the stack, there are 2 sets of indexes;positive and negative. All API function that expect a stack index as parameter can be used by passing an absolute positive index from of the stack. 0 is an invalid index.

It can sound wierd, but the negative index is the most useful because allows to write context independent code.


obat frigid|

perangsang wanita|

merangsang wanita | Health Jobs Australia | Airless Spray | obat perangsang