This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
HVENetworks's profile picture

turn a string of letters into a single number.

Started by HVENetworks, 27 March 2018 - 07:15 PM
HVENetworks #1
Posted 27 March 2018 - 09:15 PM
So, I recently got into making CC programs and I am having troubles with this

I am trying to make a string of letters into a single number.

I have done this

local letters = 'abcdefghijklmnopqrstuvwxyz'
local input = read()
local data = 0

for i=1, #input do
  local char = input:sub(i,i)
  local num = letters:find(char)
  local temp = num + data
  local data = temp
  print(data)
end
but it doesn't work. I have probably made it way too complicated than it has to be :)

Any suggestions?
Bomb Bloke #2
Posted 28 March 2018 - 06:37 AM
local data = temp

This creates a new variable in the local scope of the "for" loop. You want to use the "data" upvalue you defined before that loop started, so ditch the "local" from this line here.
Purple #3
Posted 28 March 2018 - 11:07 AM
Try this instead:


-- Read input
local input = read()
-- Convert string to int: http://www.lua.org/manual/5.1/manual.html#pdf-tonumber
local myNumber = tonumber(input)

if(myNumber == nil) then
	 -- Not a valid number, do what ever you want to do to tell the user to correct his input.
else
	 -- Valid number, do what ever you want to do with your number here.
end



Have not tested it but it should run.
HVENetworks #4
Posted 28 March 2018 - 02:45 PM
local data = temp

This creates a new variable in the local scope of the "for" loop. You want to use the "data" upvalue you defined before that loop started, so ditch the "local" from this line here.

Oh, I didn't know that. All this time, it was just a simple fix xD