Check if variable exists before assigning a value to it.

Posted: 09 Apr 2021 15:51
by luis.moya

Hello.
I want to declare variables in runtime only if it doesn't exist.
I have been looking at the scripts and it gives me the impression that it is proposed to be done but I cannot find the way.

I would like to do something like:
@set variableName=true if:ICustomVariableManager.VariableExists(variableName)=null

Thanks in advance


Re: Check if variable exists before assigning a value to it.

Posted: 09 Apr 2021 21:19
by Elringus

Hi, You can add a custom expression function for that: https://naninovel.com/guide/script-expr ... -functions


Re: Check if variable exists before assigning a value to it.

Posted: 10 Apr 2021 10:41
by luis.moya

Thanks for the quick reply.
I'm not a programmer so it took me a bit to understand how it worked, but in the end I have succeeded.
Here is the code in case someone may need it:


using Naninovel;
[Naninovel.ExpressionFunctions]
public static class MyCustomFunctions
{
public static bool VarExist (string varName) {
var variableManager = Engine.GetService<ICustomVariableManager>();
bool varExist = variableManager.VariableExists(varName);
return varExist;
}
}


and then in naninovel:
@print "variableName no exist" if:!VarExist("variableName")
@print "variableName exist" if:VarExist("variableName")