Hi

Pantelis

Member
Licensed User
Longtime User
In beginners Guide in page 273 talks about sabs and says: Global Variable cannot be a parameter. What is the meaning of this? We cannot set a name of one parameter of a sub identical to a name of a global variable? Or we cannot pass a global variable to a sub?
I try to pass a global variable to a sub and gives me no error. Looks like i works ok. When i try to set a name of a parameter with the name of a global variable the it give the error message.

So, I believe the first one is correct but the statement in the beginnersguide belongs to a section with title : Calling a sub. And the example says:

so say that "player" is a Global variable, you cannot say: PlayCard(player). Instead you have to say:
i=player: PlayCard(i)

This looks like a calling of sub and not like declaring.
But if we cannot pass a global variable to a sub then the globalvariables are unusable and usless.

Thanks.
 

Beja

Expert
Licensed User
Longtime User
i=player: PlayCard(i)


But if we cannot pass a global variable to a sub then the globalvariables are unusable and usless.

In the example you provided above, you used the global variable in a sub. what was to it is that you first assigned the variable to 'i' then used that alias in your sub.
More accurate is to say global vars can not be used directly in a sub, although I am not sure about that!!
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
You cannot do this:
B4X:
Sub Globals
    Dim NumberOfPlayers = 10 as Int
End Sub

Sub A
    Dim i As Int
    '
    i = 5
    PlayCards(i, NumberOfPlayers)
End Sub

Sub PlayCards(i As Int, MaxPlayers As Int)
    Dim p as Int
    For p = i To MaxPlayers 
        '
    Next
End Sub
You can do:
B4X:
Sub Globals
    Dim NumberOfPlayers = 10 as Int
End Sub

Sub A
    Dim i As Int
    '
    i = 5
    PlayCards(i)
End Sub

Sub PlayCards(i As Int)
    Dim p as Int
    For p = i To NumberOfPlayers
        '
    Next
End Sub
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
Sorry Klaus but you can do the first example. It is OK to pass a Global as a parameter to a Sub. What you can't do is name a parameter the same as a Global variable as if this were allowed the locally named parameter would hide access to the Global from within the Sub.
B4X:
Sub Globals
    Dim NumberOfPlayers = 10 as Int
End Sub

Sub PlayCards(i As Int, NumberOfPlayers As Int) ' not permitted
    ...
End Sub
EDIT:- Oops! I forgot to edit the code fragment - corrected now.
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…