# Setting global variable within engine - why does it work

**URL:** <https://swi-prolog.discourse.group/t/setting-global-variable-within-engine-why-does-it-work/719>\
**Category:** Help!\
**Created:** [May 24, 2019, 6:02am UTC](https://swi-prolog.discourse.group/t/setting-global-variable-within-engine-why-does-it-work/719 "2019-05-24T06:02:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![grossdan](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/grossdan/32/23_2.png) [@grossdan](https://swi-prolog.discourse.group/u/grossdan)\
**Post date:** [May 24, 2019, 6:02am UTC](https://swi-prolog.discourse.group/t/setting-global-variable-within-engine-why-does-it-work/719/1 "2019-05-24T06:02:41Z")

</div>

Hi,

To try to avoid assert as much as possible, i adapted the engine heap example to set and get a global variable. To keep the engine alive at the top level i asserted the engine reference, and an retrieving it, prior to an engine post.

I don’t understand why the b\_setval/2 / b\_getval/2 work – how is their storage associated with the engine and why do they persist.

Here is my slightly amended sample code:

The code

> :-dynamic eng/1.
> 
> create\_heap(E) :-  
> empty\_heap(H),  
> engine\_create(\_, update\_heap(H), E),  
> assert(eng(E)).
> 
> update\_heap(H) :-  
> engine\_fetch(Command),  
> ( update\_heap(Command, Reply, H, H1)  
> → true  
> ; H1 = H,  
> Reply = false  
> ),  
> engine\_yield(Reply),  
> update\_heap(H1).
> 
> update\_heap(add(Priority, Key), true, H0, H) :-  
> **\> b\_setval(global\_var, 123),**  
> add\_to\_heap(H0, Priority, Key, H).
> 
> update\_heap(get(Priority, Key), Priority-Key, H0, H) :-  
> **\> b\_getval(global\_var, X),**  
> get\_from\_heap(H0, Priority, Key, H).
> 
> heap\_add(Priority, Key) :-  
> eng(E),  
> engine\_post(E, add(Priority, Key), true).
> 
> heap\_get(Priority, Key) :-  
> eng(E),  
> engine\_post(E, get(Priority, Key), Priority-Key).

I then call it from the top level as so:

?- create\_heap(E).  
E = (7,0000017244E9FC50).

?- heap\_add(1, key1).  
true

?- heap\_get(1, K).  
K = key1 .

When running a trace, i can see that X is correctly bound to 123 in the “get” routine …

---

<div class="post-metadata">

**Author:** ![jan](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/jan/32/4_2.png) [@jan](https://swi-prolog.discourse.group/u/jan)\
**Post date:** [May 24, 2019, 6:54am UTC](https://swi-prolog.discourse.group/t/setting-global-variable-within-engine-why-does-it-work/719/2 "2019-05-24T06:54:46Z")

</div>

> [@grossdan](#):
>
> b\_setval/2 / b\_getval/2 work – how is their storage associated with the engine

Global variables live on the Prolog stacks and an engine has its own stacks. The docs do not say much about engines. They are in 99.9% the same as threads, so everything written about things being local to a thread also applies to engines.
