Reputation: 1329
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
Reputation: 7944
Alternatively,
length = math.floor(math.log10(number)+1)
Careful though, this will only work where n > 0!
Upvotes: 8
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