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

Label format recoqnition

Started by ExPfiGHtEr080, 24 January 2014 - 01:51 PM
ExPfiGHtEr080 #1
Posted 24 January 2014 - 02:51 PM
Dear,

I started to make an API, and wanted to get my api see errors and tell the user the reason,
The problem is that i have no idea how to let my program recognize if a label is a
number, string or a table. Also, is there a function to let a function recognize if a label exists?
Please help!

ExPfiGHtEr080
surferpup #2
Posted 26 January 2014 - 03:39 AM
Do you mean a computer label? There is a os.getComputerLabel() function which returns the label. If it hasn't been set, it will be nil.

There is a type() function in Lua that can tell you what type a variable is.


myVar = 1
print (type(myVar))
myVar = "1"
print (type(myVar))
myVar = {}
print (type(myVar))
local myNewVar --note no value assigned
print(type(myNewVar))
print(type(undeclaredVariable))

This program will output:


number
string
table
nil
nil

As for existence, if a variable is nil, it is false. If it is assigned it will evaluate as true.

So, you can test a variable. Ex.


local myVar
if myVar then
  print "It exists"  
else
  print "Nope, it is nil."
end

--Result
--Nope, it is nil.

This is useful in Lua, because it allows you to assign values in functions when they are nil:


local myEmptyVar
local myOtherVar = 3
myEmptyVar = myEmptyVar or 10
myOtherVar = myOtherVar or 25

print(myEmptyVar)
print(myOtherVar)

--Result
--10
--3

For additional error checking, you may want to check out the pcall() function (protected call) and the assert() function.

For assert and a useful website, check The.Lua.Tutorial. You can try out Lua commands there interactively, or just use the Lua interactive mode in ComputerCraft (see Computer Basics 1 by Lyqyd

Does that point you in the right direction?
Edited on 26 January 2014 - 02:51 AM
ExPfiGHtEr080 #3
Posted 26 January 2014 - 08:16 AM
surferpup, Thank you so much! thats exactly what i needed :)/> Ill look at you when i need more help
surferpup #4
Posted 26 January 2014 - 04:59 PM
Lot of amazing coders who give great advice on this site. Just saying.