github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/warn.go (about) 1 package runtime 2 3 import ( 4 "fmt" 5 "io" 6 "strings" 7 ) 8 9 // Warner is the interface for the Lua warning system. The Warn function emits 10 // warning, when called with one argument, if the argument starts with '@' then 11 // the message is a control message. These messages are not emitted but control 12 // the behaviour of the Warner instance. 13 type Warner interface { 14 Warn(msgs ...string) 15 } 16 17 // The default Warner type. It logs messages to a given io.Writer. Note that 18 // it is off by default. Issue Warn("@on") to turn it on. 19 type LogWarner struct { 20 on bool 21 dest io.Writer 22 pfx string 23 } 24 25 var _ Warner = (*LogWarner)(nil) 26 27 // NewLogWarner returns a new LogWarner that will write to dest with the given 28 // prefix. 29 func NewLogWarner(dest io.Writer, pfx string) *LogWarner { 30 return &LogWarner{dest: dest, pfx: pfx} 31 } 32 33 // Warn concatenates its arguments and emits a warning message (written to 34 // dest). It understands two control messages: "@on" and "@off", with the 35 // obvious meaning. 36 func (w *LogWarner) Warn(msgs ...string) { 37 if len(msgs) == 1 && len(msgs[0]) > 0 && msgs[0][0] == '@' { 38 // Control message 39 switch msgs[0] { 40 case "@on": 41 w.on = true 42 case "@off": 43 w.on = false 44 } 45 return 46 } 47 if w.on { 48 fmt.Fprintf(w.dest, "%s%s\n", w.pfx, strings.Join(msgs, "")) 49 } 50 }