The three ways in AppGameKit of passing stuff into functions (and not use evil globals):
type myString_t
foo as string
endType
main()
function main()
myString as myString_t
myString.foo = "in main"
print("Foo " + myString.foo)
passByValueNoReturn(myString.foo)
print("Foo " + myString.foo)
myString.foo = passByValueWithReturn(myString.foo)
print("Foo " + myString.foo)
passByReference(myString)
print("Foo " + myString.foo)
sync()
repeat
// pause
until GetRawKeyPressed(32)
endFunction
function passByValueNoReturn(in as string)
in = "from just passing in"
endFunction
function passByValueWithReturn(in as string)
in = "from passing in and out of function"
endFunction in
function passByReference(in ref as myString_t)
in.foo = "from passing by reference into function"
endFunction
I created a type to hold the string, just to demonstrate the pass by reference method. That will only work with user-defined types - not the built in ones. Types are great for holding data that belong together. for instance with sprites, you may create a sprite properties type like so:
type spriteProp_t
id as integer
x as integer
y as integer
w as integer
h as integer
state as integer
endType
The '_t' suffix is just an old habit of mine to differentiate types from more normal arrays and variables. Using that type you can define as many sprites you'd like by creating variables and arrays of that type.
But that is not the topic here. So. In the code example, in the first function call, a value is simply passed to the function with no return. Whatever happens to that variable in that function stays in that function. Sort of like Las Vegas, only without gambling, booze and, uhm, ladies of the night?
In the second function, a value is passed in *and* passed out (aka returned). So you send it in in one state, and is returned in another. You do not need send and return the same variable - or send anything at all. You could replace it with this:
function passNoValueWithReturn()
endFunction "with nothing in and new out"
and call it in main() with foo = passNoValueWithReturn()
The possibilities are endless. Anyhow, the last is passing by reference - or by pointer in other languages. Without getting into technicalities, this is very useful for larger datasets. When passing by value, the program copies the value and pass it in. Which is fine for discrete variables. Not that great for a complex array of types. By passing by reference, there is no copying going on, it operates directly on the type where it is stored in memory instead. This is the fastest way to have a function change your data.
...well, apart from using globals. But using globals all over the place will ensure an unholy mess sooner or later. So save those for IDs of your assets and maybe one type holding a global state. Everything else, pass it around to keep control.