xysun
xysun

Reputation: 2015

Ocaml Graphics.open_graph won't work in script mode

I'm trying to use the ocaml graphics module. The line:

#Graphics.open_graph "";;

works fine in the interactive module, i.e. a small window pop up in X11 with white background. However, when I try to use the script mode -- put this line in a file then compile it:

ocamlc -o a.out graphics.cma code.ml

only X11 starts but with no window popup. Am using a mac. Anyone knows why? Thanks.


Followup:

It seems under script mode the popup window will closeup immediately after code execution. Because if I compile using XTerminal, I can see a small window popup but then closes.

I managed to keep the window open by adding an infinit loop at the bottom:

while true do () done;;

But still don't understand how things really work. Please help. Thanks.

Upvotes: 1

Views: 1185

Answers (2)

gasche
gasche

Reputation: 31469

Indeed, as jrouquie explains you need to delay the termination of your program. The way I personally do that is by waiting on user input. At the end of the interactive program (or function being studied that opens the graphic mode), I put:

ignore (Graphics.read_key ())

This will wait until a key has been hit on the keyboard, and ignore the key value before returning.

Upvotes: 1

jrouquie
jrouquie

Reputation: 4425

All ressources are freed when the script terminates: memory, file descriptors, including the X window.

If you add an infinite loop, the script does not terminates, and the windows stays open.

Likewise, under the toplevel, the window stays open as long as you don't close the toplevel.

I would suggest to add two lines add the end of your script:

  • print "press enter to exit"
  • read one line from keyboard input

This way the script will not terminate until the user presses enter.

Upvotes: 3

Related Questions