Page 1 of 1

How to update a variable in a procedure

Posted: Sun Mar 10, 2019 3:49 am
by coco2
I'm still a bit of a beginner, so sorry if this has been asked before.

We can't pass a pointer to a primitive (integer etc) in a procedure so how do we change a variable? Make it global?

Re: How to update a variable in a procedure

Posted: Sun Mar 10, 2019 4:17 am
by TI-994A
coco2 wrote:...can't pass a pointer to a primitive (integer etc) in a procedure so how do we change a variable?

Code: Select all

Procedure passByRef(*myInt, *myString)
  PokeI(*myInt, 456)
  PokeS(*myString, "World")
EndProcedure

myInt = 123
myString.s = "Hello"

Debug myInt
Debug myString

passByRef(@myInt, @myString)

Debug myInt
Debug myString

Re: How to update a variable in a procedure

Posted: Sun Mar 10, 2019 5:28 am
by coco2
Thanks I guess I'll have to do it that way then. Any idea why PB doesn't have pointers to primitive types?

Re: How to update a variable in a procedure

Posted: Sun Mar 10, 2019 6:28 am
by Demivec
coco2 wrote:Thanks I guess I'll have to do it that way then. Any idea why PB doesn't have pointers to primitive types?
Here is a modified version of TI-994A's sample. His example covers one way of doing things, here's another. I think this was more along the lines of what you were asking.

Code: Select all

;Structures for primitive PureBasic types (and each of their solitary sub-elements):
;BYTE\b.b, ASCII\a.a, UNICODE\u.u, LONG\l.l, INTEGER\i.i, QUAD\q.q, STRING\s.s
;
;To pass a reference to a string it is often easier to assign it to the same
;structure that PureBasic uses.  If this is not done more steps are involved.
;

Procedure passByRef(*myInt.Integer, *myString.string)
  *myInt\i = 456
  *myString\s = "World"
EndProcedure

myInt = 123
myString.string\s = "Hello"


Debug myInt
Debug myString\s

passByRef(@myInt, @myString)

Debug myInt
Debug myString\s

Re: How to update a variable in a procedure

Posted: Sun Mar 10, 2019 6:38 am
by coco2
I see so PureBasic does pass pointers to primitive types, you just have to do it a special way

Re: How to update a variable in a procedure

Posted: Sun Mar 10, 2019 7:21 am
by TI-994A
coco2 wrote:...so PureBasic does pass pointers to primitive types...
Not really. Those are convenience structures; not native types.

Here's another approach:

Code: Select all

Procedure passByRef(*myInt, *myString)  
  *intStructure.INTEGER = *myInt
  *stringStructure.STRING = @*myString
  *intStructure\i = 456
  *stringStructure\s = "World!"  
EndProcedure

myInt = 123
myString.s = "Hello"

Debug myInt
Debug myString

passByRef(@myInt, @myString)

Debug myInt
Debug myString