Is it possible to make up var names as strings at runtime?

Started by bx83, Wed 28/04/2021 08:00:28

Previous topic - Next topic

bx83

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.

Snarky


Crimson Wizard

#2
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 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

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

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

and you call this function like:
Code: ags

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



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

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

SMF spam blocked by CleanTalk