Task

Show how to return more than one value from a function.




' FB 1.05.0 Win64
 
' One way to return multiple values is to use ByRef parameters for the additional one(s)
Function tryOpenFile (fileName As String, ByRef fileNumber As Integer) As Boolean
   Dim result As Integer 
   fileNumber = FreeFile
   result = Open(fileName For Input As # fileNumber)
   If result <> 0 Then
     fileNumber = 0
     Return False
   Else
     Return True
   End If
End Function
 
Dim fn As Integer
Var b = tryOpenFile("xxx.zyz", fn) '' this file doesn't exist
Print b, fn
b = tryOpenFile("input.txt", fn) '' this file does exist
Print b, fn
Close # fn
 
' Another way is to use a user defined type
 
Type FileOpenInfo
  opened As Boolean
  fn As Integer
End Type
 
Function tryOpenFile2(fileName As String) As FileOpenInfo
   Dim foi As FileOpenInfo 
   foi.fn = FreeFile
   Dim result As Integer
   result = Open(fileName For Input As # foi.fn)   
   If  result <> 0 Then
     foi.fn = 0
     foi.opened = False
   Else
     foi.Opened = True
   End If
   Return foi
End Function
 
Print
Var foi = tryOpenFile2("xxx.zyz") 
Print foi.opened, foi.fn
foi = tryOpenFile2("input.txt")
Print foi.opened, foi.fn
Close # foi.fn
 
Print
Print "Press any key to quit"
Sleep