github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/cmd/golua-repl/main.go (about)

     1  package main
     2  
     3  import (
     4  	_ "embed"
     5  	"flag"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"log"
     9  	"os"
    10  
    11  	"github.com/arnodel/edit"
    12  )
    13  
    14  //go:embed init.lua
    15  var defaultInitLua []byte
    16  
    17  func main() {
    18  	flag.Usage = usage
    19  	dumpAtEnd := false
    20  	flag.BoolVar(&dumpAtEnd, "d", false, "Dump session to terminal when quitting")
    21  	flag.Parse()
    22  
    23  	// Log to a file because the terminal is used
    24  	// f, err := os.OpenFile("testlogfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    25  	f, err := ioutil.TempFile("", "golua-repl.logs.")
    26  	if err != nil {
    27  		log.Fatalf("error opening file: %s", err)
    28  	}
    29  	defer f.Close()
    30  	log.Printf("Logging to %s", f.Name())
    31  	log.SetOutput(f)
    32  
    33  	// Initialise the app
    34  	buf := NewLuaBuffer()
    35  	win := edit.NewWindow(buf)
    36  	if dumpAtEnd {
    37  		defer buf.WriteTo(os.Stdout)
    38  	}
    39  
    40  	app := edit.NewApp(win)
    41  	if err := app.InitLuaCode("[builtin init]", defaultInitLua); err != nil {
    42  		log.Fatalf("error in init file: %s", err)
    43  	}
    44  
    45  	// Initialise the screen
    46  	screen, err := edit.NewScreen()
    47  	if err != nil {
    48  		log.Fatalf("error getting screen: %s", err)
    49  	}
    50  	defer screen.Cleanup()
    51  
    52  	// Event loop
    53  	for app.Running() {
    54  		app.Draw(screen)
    55  		app.HandleEvent(screen.PollEvent())
    56  	}
    57  }
    58  
    59  func usage() {
    60  	fmt.Fprintf(flag.CommandLine.Output(), "Help for %s:\n%s\nUsage:\n", os.Args[0], helpMessage)
    61  	flag.PrintDefaults()
    62  }
    63  
    64  const helpMessage = `
    65  golua-repl is a REPL for golua.  It lets you run lua statements interactively.
    66  
    67  Highlights:
    68    - Type a Lua chunk, press [Enter] to execute it.
    69    - Quit with [Ctrl-D]
    70    - You can also type an expression and it will be evaluated
    71    - The last result is available via _ (_2, _3 fi there are multiple values)
    72    - Use the mouse / scrollwheel to navigate
    73    - Select a region with the mouse, use system clipboard to paste
    74    - Press [Enter] when on a previously executed statement to edit a copy of it
    75  `