Some notes about variables and lists

I thought it would be good to share some things I’ve learned about variables and lists in Dialog (and Prolog too).

Firstly, variables are first class objects: they exist in memory (created when needed), they are passed to a query by their address, other variables can refer to them, and they can be stored in lists. That is why it is possible to create a list containing new variables, and bind those variables at a later time.

That is quite different from languages like C where local variables of a function exist in a stack frame, and once the function returns those variables cease to exist.

In the following example…

(program entry point)
	($X = 1)
	($Y = 2)
	($Z = 3)
	($List = [$X $Y $Z])
	The list is: $List. (line)

…with other programming languages, the created list would contain three scalar values (1, 2 and 3). However in Dialog, the list actually contains three variables, and printing the list shows their bound values.

Secondly, Dialog does not do garbage collection, so in a complex procedure like a sorting algorithm or a graph traversal algorithm, each newly created list (some with newly created variables) will use up some memory, and it won’t be become free again until the algorithm has finished and the game returns to the main loop.

For Dialog, that is a perfectly reasonable design decision, especially for its targets of the Z-machine and the 8-bit Å-machine, where a GC would be overkill.

Nevertheless this design does explain why complex algorithms like a merge sort can run out of memory when trying to sort a list of 50 numbers – there is simply a lot of intermediate results which are not needed, but they don’t get freed while the algorithm is running.

Thirdly, Dialog allows storing lists in a global variable or object property. The manual states that these lists must be fully bound, i.e. any variables in them must be bound, and the reason should now be clear: those variables will cease to exist once the game returns to the main loop!

Also when storing a list in a global, the list is rebuilt so that the bound variables are replaced by the value they are bound to.

1 Like

Am I understanding this right if I say that essentially what you’re saying is unbound variables are first-class objects?

Except for $ (the anonymous variable), all variables are first class objects, and even unbound ones require a piece of memory.

1 Like