Squirrel - Optional Parameters not set -> abort. - by Daraan
Daraan on 27/3/2017 at 14:31
I know you guys are new to this too but maybe your old knowledge can help.
For a script I want to have 3 optional parameters in the Design Note, accessible via userparams().Name (a squirrel table).
But if a parameter is not set and I call it via userparams().Name the script immediately aborts.
So I can't even do a 'if (userparams().Name != null)' check:erg:
Any idea how I could test if a parameter is set and still continue even if not?
The Watcher on 27/3/2017 at 15:20
Disclaimer: I've only the most passing experience with Squirrel, so this may be total rubbish...
What you probably need to do is catch the exception, so something like
Code:
name = "";
try {
name = userparams().Name;
} catch(err) {
name = "Some default";
}
... now use name...
Daraan on 27/3/2017 at 16:34
Perfect solution :angel:
Thank you.
Good to know another keyword :)
Telliamed on 29/3/2017 at 06:13
Code:
local name = "Name" in userparams() ? userparams().Name : "NoName";
The Watcher on 29/3/2017 at 07:08
That'd be a better approach, yeah!
caffeinatedzombeh on 29/3/2017 at 08:19
[quote =Daraan;2352817]Thank you caffe. Great info.
Edit: Did I get this right _get would also work and would be faster than in checks?The three ways of dealing with an index that might not be there are:
setting a default, trying it and catching and ignoring the runtime error
Code:
local tParams = userparams()
local x = 0;
try
{
x = tParams.XParamName;
}
catch(ex)
{} // nothing in the catch as we already set a value against it and it'll throw an error at the . and not do the =
Not the ideal way to handle that sort of thing, I would only tend to do that if I was doing tointeger or tofloat on it that *that* might throw an error if you can't pre-know the content of the string is going to be a number
in
Code:
local tParams = userparams()
local x = 0;
if ("XParamName" in tParams)
{
x = tParams.XParamName;
}
tidier, more obvious, faster
metafunctions and delegates
Code:
local tAllValuesDefaultToZero = {_get = function(index){ return 0;}}; // this _get function will be called when you try to access an index that isn't there (the index is passed to it)
local tParams = userparams();
tParams.setdelegate(tAllValuesDefaultToZero ); // tell the VM that we want to use that _get on this table
local x = tParams.XParamName;
Total overkill for what you're using it for and probably not the right answer for anything in a thief script but useful to know, tend to use that sort of thing for when I'm passing two very similar data structures to the same code and don't want to have to care which of the two it is.
The other thing to notice from the code in your other thread is that I did local tParams = userparams() then accessed tParams multiple times. That is MUCH faster than calling userparams multiple times