Skip to content

Commit fdb25cc

Browse files
Handle infinity and NaN for string.format()
1 parent 67d1beb commit fdb25cc

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed

internal/lua/stringlib.go

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -311,12 +311,45 @@ func stringFormat(ctx context.Context, l *State) (int, error) {
311311
if err != nil {
312312
return 0, err
313313
}
314-
if c == 'a' || c == 'A' {
315-
// Hexadecimal float. Go uses 'x'/'X'.
316-
spec = spec[:len(spec)-1] + string(c+('X'-'A'))
314+
315+
isUpper := (c >= 'A' && c <= 'Z')
316+
if math.IsNaN(n) {
317+
var s string
318+
if isUpper {
319+
s = "NAN"
320+
} else {
321+
s = "nan"
322+
}
323+
324+
spec = spec[:len(spec)-1] + "s"
325+
fmt.Fprintf(sb, spec, s)
326+
} else if math.IsInf(n, 0) {
327+
var s string
328+
if isUpper {
329+
s = "INF"
330+
} else {
331+
s = "inf"
332+
}
333+
if n < 0 {
334+
s = "-" + s
335+
} else {
336+
options := spec[1 : len(spec)-1]
337+
if strings.Contains(options, "+") {
338+
s = "+" + s
339+
} else if strings.Contains(options, " ") {
340+
s = " " + s
341+
}
342+
}
343+
344+
spec = spec[:len(spec)-1] + "s"
345+
fmt.Fprintf(sb, spec, s)
346+
} else {
347+
if c == 'a' || c == 'A' {
348+
// Hexadecimal float. Go uses 'x'/'X'.
349+
spec = spec[:len(spec)-1] + string(c+('X'-'A'))
350+
}
351+
fmt.Fprintf(sb, spec, n)
317352
}
318-
// TODO(now): Special floats.
319-
fmt.Fprintf(sb, spec, n)
320353
case 'p':
321354
if arg > top {
322355
return 0, NewArgError(l, arg, "no value")

0 commit comments

Comments
 (0)