Android Question can i set/change a variable when i pass it as parameter ?

Addo

Well-Known Member
Licensed User
i am trying to create a sub in another Module to set some local variables in a parameter

as example


B4X:
dim var as string

setvarstring(var)

log(var) 'This should be = something  can i do that ?


sub setvarstring(avar as string)

avar = "something"

end sub
 

lucasheer

Active Member
Licensed User
Longtime User
Basic4android follows Java parameter passing. Objects are passed by reference and "primitives" are passed by value.
Arrays are objects so are always passed by reference.

Since 'avar' is a string, it's being passed as a value. If you want to change the value of that specific variable, you'll have to reference it through it's module.

OR

return the value and change it from the original module:

B4X:
Dim var As String

var = setvarstring(var)

Log(var) 'This should be = something  can i do that ?


Sub setvarstring(avar As String)

    Return "something"

End Sub
 
Upvote 0

lucasheer

Active Member
Licensed User
Longtime User
then i should return it as string ? i cant set it directly without using return ?

You can reference the other module like:

B4X:
Sub setvarstring(avar As String)

    othermodule.var = "something"

End Sub

The problem is that it's passing your string as a value instead of a reference. Look at ByRef vs ByVal
 
Upvote 0

Brian Dean

Well-Known Member
Licensed User
Longtime User
i am trying to create a sub in another Module ...
You cannot do this in the way you illustrate, as I think that you understand (arguments are passed by value). But there are alternative ways to get values into one module from another - global variables are the obvious one, but using a class object with properties (which are in fact subroutines in another module) is often a better scheme.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
i am trying to create a sub in another Module to set some local variables in a parameter
Declare a custom type with all the fields and pass it, or better create a sub that creates one and returns it.

In some esoteric cases where it does make sense to pass variables by reference then you can use arrays:
B4X:
Dim str(1) As String
SomeSub(str)

Sub SomeSub(str() As String)
 str(0) = "aaa"
End Sub
 
Upvote 0
Top