Erroneous or misleading code snippet?

3 posts / 0 new
Last post
Bert_B
Offline
Joined: 11/04/2020 - 06:46
Erroneous or misleading code snippet?

Dear Brian,
While googling I found the following code snippet on this website:
https://www.ideascripting.com/wiki/check-if-field-exists
It should be a code snippet that basically checks if a field exists or not. So I would expect that if that function returns true it does exist and if it returns false the field does not exist. However, the code snippet is wrong/misleading:
Set field = table.GetField(sFieldname)
If err.number = 0 Then
checkIfFieldExists = False
err.number = 0
Else
checkIfFieldExists = True
End If
Set field = Nothing

Now it is programmed in such way that if the field exists and no error is created (err.number =0) then it puts the boolean to false. If the field does not exists and error is raised, the error number is not equal to zero (in my case it is a negative number -xxxxx whatever) and the checkIfFieldExists boolean is set to true.
From my opinion it should be the other way round. Or?

Brian Element's picture
Brian Element
Offline
Joined: 07/11/2012 - 19:57

HI Bert_B,

I think this is a misunderstanding of what the code is doing.  It is looking to see if the name of the field you are sending to the snippet exists not if the name of the field already exists in the database.  This is why it returns true if the field name already exists as you are looking for a field name that doesn't exists.

Bert_B
Offline
Joined: 11/04/2020 - 06:46

Mh, I am not understanding it.
 
"This is why it returns true if the field name already exists"
 
Thanks for your reply, however this is exactly what I mean. Please check if carefully. Because:
 
=> It returns false if the field name already exists.
 
Explanation: I "give into" the function a database (filename) and a fieldname. It opens the database / file and tries to set the field variable equal to
table.GetField(sFieldname)
 
If the field name already exists then it works and no error is created and error number is equal to 0. Therefore it is set to false. If the field name does not exist in the file then it does not work and an error number not equal to 0 is created (in my case negative number) and it is set to true. This is what I mean, it should be the other way round. I also checked it with a dataset example.