Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: bx83 on Wed 28/04/2021 08:00:28

Title: Is it possible to make up var names as strings at runtime?
Post by: bx83 on Wed 28/04/2021 08:00:28
In AGS, is it possible to use substitutions to write a variable name, and then keep it as a symbol?

I'm trying to write a for loop which goes numbers 1 to 4, and then changes properties of a GUI control with a set name 'Load4' or 'Load3' etc.

Can I write e.g. LoadX or String.Format("Load%d",x), etc?

Bit of a stretch but I thought someone might have a solution for runtime symbol names.
Title: Re: Is it possible to make up var names as strings at runtime?
Post by: Snarky on Wed 28/04/2021 08:24:49
No, this is in no way possible.
Title: Re: Is it possible to make up var names as strings at runtime?
Post by: Crimson Wizard on Wed 28/04/2021 08:50:36
This is possible to accomplish, except not as directly.
But what bx83 is asking about is probably adressing objects not by their explicit script names to avoid code duplication. I guess this may be related to the code posted here (https://www.adventuregamestudio.co.uk/forums/index.php?topic=59066.0) where he has 4 copies of function which do same thing to 4 different GUI controls.

In AGS, and everywhere else, this is usually done by either passing object as a pointer into a function, or placing objects in arrays and then adressing them with array index.

Fortunately AGS already has all objects in arrays (and you may create your own for convenience too).
So, for example, if your buttons or other objects have sequential IDs, you may do something like:

Code (ags) Select

for (int i = FirstID; i <= LastID; i++) {
    Button *button = gMyGUI.Controls[i].AsButton;
    // do something with button
}


EDIT: another variant with function would look like:
Code (ags) Select

function DoSomethingToButton(Button *but) {
    // do something with button
}

and you call this function like:
Code (ags) Select

DoSomethingToButton(btnLoad1);
DoSomethingToButton(btnLoad2);
DoSomethingToButton(btnLoad3);
DoSomethingToButton(btnLoad4);



or even merge with the "for loop" variant:
Code (ags) Select

for (int i = FirstID; i <= LastID; i++) {
    DoSomethingToButton(gMyGUI.Controls[i].AsButton);
}