Trying to create a function

U

unba1300

Guest
I've created this function so that I can call it and get a random result each time:
B4X:
Sub PickTrait (Trait As String)
i = Rnd(0, lstTraits.Size)
Return lstTraits.Get(i)
End Sub
And trying to call it from another sub like this:
B4X:
PickTrait(Trait1)
PickTrait(Trait2)
sb.Append(Trait1).Append(" and ").Append(Trait2)
I don't get any errors, but nothing is getting picked from the list.
 
U

unba1300

Guest
I think I got it (at least this works):
B4X:
Sub PickTrait
i = Rnd(0, lstTraits.Size)
Return lstTraits.Get(i)
End Sub
Calling sub:
B4X:
Trait1 = PickTrait
Trait2 = PickTrait
sb.(Trait1).Append(" and ").Append(Trait2)
 
Upvote 0

timwil

Active Member
Licensed User
Longtime User
When you do a function you have to say what it returns;

Sub PickTrait (Trait As String)
i = Rnd(0, lstTraits.Size)
Return lstTraits.Get(i)
End Sub

should be

Sub PickTrait (Trait As String) AS STRING
i = Rnd(0, lstTraits.Size)
Return lstTraits.Get(i)
End Sub

If you put the as string in brackets it expects those as parameters to the function!
 
Last edited:
Upvote 0
U

unba1300

Guest
I'm not very clear about how it's returning something without being passed anything. The sub name has no () after it. I haven't been programming since the mid 90's with VB, so I'm very rusty. I seem to be addicted to B4A though. Gotta make an app!
 
Upvote 0
U

unba1300

Guest
Thank you timwil. I replied to the previous post before reading yours. I'll go try that.
 
Upvote 0
U

unba1300

Guest
Here's what I've done after some more reading. A function that doesn't get passed a parameter, but returns a string:
B4X:
Sub PickTrait() As String
  i = Rnd(0, lstTraits.Size)
  Return lstTraits.Get(i)
End Sub
And part of the calling sub:
B4X:
Trait1 = PickTrait
Trait2 = PickTrait
sb.Append(Trait1).Append(" and ").Append(Trait2)
Seems to work fine. Whatever I return, gets assigned to the calling variable.
 
Upvote 0
Top