In the direction of string to number , the tonumber() function takes an optional second argument, which indicates the base to use, which can be from 2 to 36 with an obvious value for digits in the bases greater than 10.
In the direction of the number to the lines, this can be done a little more effectively than Nicholas's answer in approximately the following way:
local floor, insert = math.floor, table.insert
function basen (n, b)
n = floor (n)
if not b or b == 10 then return tostring (n) end
local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local t = {}
local sign = ""
if n <0 then
sign = "-"
n = -n
end
repeat
local d = (n% b) + 1
n = floor (n / b)
insert (t, 1, digits: sub (d, d))
until n == 0
return sign .. table.concat (t, "")
end
This creates fewer garbage lines to collect using table.concat() instead of calling the string concatenation operator repeatedly .. Although this is not very practical for small lines, this idiom should be studied, because otherwise, building a buffer in a loop with a concatenation operator will tend to have O (n 2 ) table.concat() , and table.concat() were designed to do much better.
The question remains unanswered whether it is more efficient to output the numbers on the stack in table t with calls to table.insert(t,1,digit) or add them to the end with t[#t+1]=digit , and then call string.reverse() to put the numbers in the correct order. I will leave the benchmarking student. Please note that although the code I pasted here is running and appears to be getting the correct answers, there may be other possibilities for changing it further.
For example, the general case of base 10 is selected and handled by the built-in tostring() function. But similar culling can be done for bases 8 and 16, which have conversion specifiers for string.format() ( "%o" and "%x" , respectively).
In addition, neither the Nikolaus solution nor my pen handles non-integer numbers very well. I emphasize that here, forcing the value of n integer with math.floor() at the beginning.
The correct conversion of the total floating-point value to any base (even base 10) is fraught with subtleties, which I leave as an exercise for the reader.