Lua, 147 Bytes
I don't think I can golf it down a lot more, I've tested a lot of ways to do it, and here come the shortest. Even using an old compiler which contains the deprecated function table.foreach(table,function)
doesn't shave off some bytes.
This program takes a string as argument, and print the concatenation of a table values separated by spaces.
t={}for _,i in pairs({8,10,16})do x=tonumber(arg[1],i)x=x and x or 0 t[#t+1]=127>x and 19<x and string.char(x)or nil end print(table.concat(t," "))
Ungolfed and explanations
t={} -- Initalise the array containing the chars to print
for _,i in pairs({8,10,16}) -- Iterate over the array {8,10,16}
do
x=tonumber(arg[1],i) -- convert the input in base i to a number in base 10
x=x and x or 0 -- if the input wasn't a number, x is nil
-- use a ternary operator to set x in this case
t[#t+1]=127>x and 19<x -- if x is the bytecode of a printable character
and string.char(x)or nil-- insert this character into t
end
print(table.concat(t," ")) -- concatenate the values in t with " " as separator
-- and print it
If you're wandering why there's a variable set but not used in a golfed code (the variable _
in the for loop), here's why:
You have 2 ways to iterate over an array in Lua, either in a for style:
for i=1,#table do --[[code here, use table[i] ]] end
or in a foreach style:
for key,value do pairs(table) do --[[code here]] end
I was needing the values contained in the table {8,10,16}
as they are the different bases I have to iterate over. But functions with multiple return won't allow you to chose which one you actually want to be returned, they follow an order. To have the variable value
set, I need to catch the value of key
too: that's what we call a dummy _
.