Ok so I'm not too sure why you're doing that loop, and why your'e doing it. One of your main problems is that you're also localising your variables in those loops, you don't want to localise
a and
b inside the loops otherwise you forget the numbers you just made. A suggestion I would make is to remove the loop in your
getDecimal and to do the following
local function getDecimal(place,code)
--# if the string number was 1
if string.sub(code,place,place) == "1" then
--# return 2 to the power of the length (since binary is base-2) minus the currently checking position (since binary is right->left not left->right)
return 2^(#code - place)
end
--# else return 0
return 0
end
Then just remove that local in your
b loop and you should be good.
However that being said, this method that you're using is quite slow, and there is already a way to do this in Lua that is much quicker! Just use tonumber and tell it that the string is in base 2... Ultimate solution:
term.clear()
term.setCursorPos(1,2)
write("Binary number: ")
local binary = read()
local b = tonumber(binary, 2)
if not b then
error("Input not binary", 0)
end
print( binary.." in decimal is "..b )