Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a lua string with a boolean variable?

I have a boolean variable whose value I'd like to display in a formatted string. I tried using string.format, but get something like the following for any choice of format option listed in the language reference:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio > print(string.format("%c\n", true)) stdin:1: bad argument #2 to 'format' (number expected, got boolean) stack traceback:     [C]: in function 'format'     stdin:1: in main chunk     [C]: ? 

I can get the boolean to display by adding a tostring,

> print(string.format("%s\n", tostring(true))) true 

but that seems rather indirect to this lua beginner. Is there an formatting option I've overlooked? Or should I use the above approach? Something else?

like image 246
Michael J. Barber Avatar asked Jul 07 '11 18:07

Michael J. Barber


People also ask

What does %s mean in Lua?

Lua uses %s in patterns (Lua's version of regular expressions) to mean "whitespace". %s+ means "one or more whitespace characters".

Does Lua have Booleans?

This is a short introduction to the eight basic types of values in Lua: number, string, boolean, table, function, nil, userdata, thread.


2 Answers

Looking at the code of string.format, I don't see anything that supports boolean values. I guess tostring is the most reasonable option in that case.

Example:

print("this is: " .. tostring(true))  -- Prints:   this is true 
like image 100
Omri Barel Avatar answered Sep 22 '22 13:09

Omri Barel


In Lua 5.1, string.format("%s", val) requires you to manually wrap val with tostring( ) if val is anything other than a string or number.

In Lua 5.2, however, string.format will itself call the new C function luaL_tolstring, which does the equivalent of calling tostring( ) on val.

like image 37
dubiousjim Avatar answered Sep 22 '22 13:09

dubiousjim