Robert Kerr
Robert Kerr

Reputation: 1329

Find the string length of a Lua number?

Easy question here, probably, but searching did not find a similar question.

The # operator finds the length of a string, among other things, great. But with Lua being dynamically typed, thus no conversion operators, how does one type a number as a string in order to determine its length?

For example suppose I want to print the factorials from 1 to 9 in a formatted table.

i,F = 1,1
while i<10 do
    print(i.."! == "..string.rep("0",10-#F)..F)
    i=i+1
    F=F*i
end

error: attempt to get length of global 'F' (a number value)

Upvotes: 3

Views: 10086

Answers (4)

Yan
Yan

Reputation: 1

Isn't while tostring(F).len < 10 do useful?

Upvotes: 0

HennyH
HennyH

Reputation: 7944

Alternatively,

length = math.floor(math.log10(number)+1)

Careful though, this will only work where n > 0!

Upvotes: 8

BMitch
BMitch

Reputation: 265180

There are probably a dozen ways to do this. The easy way is to use tostring as Dan mentions. You could also concatenate an empty string, e.g. F_str=""..F to get F_str as a string representation. But since you are trying to output a formatted string, use the string.format method to do all the hard work for you:

i,F = 1,1
while i<10 do
    print(string.format("%01d! == %010d", i, F))
    i=i+1
    F=F*i
end

Upvotes: 5

Dan D.
Dan D.

Reputation: 74685

why not use tostring(F) to convert F to a string?

Upvotes: 13

Related Questions