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

Check variables type

Started by Bye., 23 November 2015 - 08:46 PM
Bye. #1
Posted 23 November 2015 - 09:46 PM
I need to check the type of a variable:


A = 1
B = "Text"

How can I determine if A is a number or a string and the same for B?

I think something like this


function checkVar(var)
if var is a string then
return "string"
elseif var is a number then
return "number"
elseif var is boolean then
return "boolean"
end
end

Thank you!
Bomb Bloke #2
Posted 23 November 2015 - 10:02 PM
The type() function serves this purpose.
Dragon53535 #3
Posted 24 November 2015 - 12:30 PM

type(93) --# "number"
type("Hello person") --# "string"
type(function() print("hi") end) --# "function"
type({1,2,3,4,5}) --# "table"
Bye. #4
Posted 24 November 2015 - 05:00 PM
Thank you a lot!
Edited on 24 November 2015 - 04:00 PM
Bye. #5
Posted 25 November 2015 - 06:41 PM
Now I have another one problem…

I'm using this code to wait an input


key = read()

I need to check if the input is a set of numbers like 123456 or a string like "abcdef" but this code put the datas in a string variable and if I do


if type(key) == "string" then
   tonumber(key)
end

with a number there will be no problem but if I try to do this with a word the computer will report an error

My question is: how can I check if in string variable there is a number and then convert it or if there is a word?
Dog #6
Posted 25 November 2015 - 06:53 PM
If you tonumber a string such as "ASDF" the result will be nil. Addtionally, read() returns a string, so your first string check isn't necessary. Try this…

local tmpNum = tonumber(key) --# hold our tonumbered string in a new variable
if tmpNum then --# if the new variable is not nil (which means, in this case, it's a number)
  key = tmpNum --# set key to the new number value (otherwise 'key' is left alone)
end

After doing that, you can then type the variable 'key' to see what you've got (a number or a string).


if type(key) == "string" then
  --# do string stuff
else
  --# do number stuff
end

There are, no doubt, better ways to approach this (you could even combine the two snippets into one), but this should get you going in the right direction.
Edited on 25 November 2015 - 06:07 PM
Awe2K #7
Posted 25 November 2015 - 07:38 PM
To check if your string contains only numbers, just try to find matches with regex:


if (string.match(string_you_have_read, "^[0-9]*$")) then
-- It's a number
else
-- It's not a number, maybe print some error, or something else
end

Edit: well, forum breaks my code…
Edited on 25 November 2015 - 06:39 PM
Bye. #8
Posted 25 November 2015 - 09:03 PM
Thank you Dog and Awe2K!