• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

if error then do the or

RizbIT

Member
if you have a list and you run find value and nothing is found can you just add an or to set a value

for example can you do this
var dbid = ds_list_find_value(list1,1) or 0;

so if value list position 1 is undefined then it will set var dbid as 0 ?
 

CloseRange

Member
I belive just do this:
Code:
var dbid = ds_list_find_value(list1, 1);
if (is_undefined(dblid)) {
    ds_list_replace(list1, 1, 0);
    dblid = 0;
}
 

CloseRange

Member
hmm no I don't belive you can get simpler than that unless you are using gm2 by using ternary operators:
Code:
var dbid = ds_list_find_value(list1, 1);
      dbid = is_undefined(dbid) ? 0 : dbid;
except that code will not actually set the value in ds_list to 0.
so it's the equivalent to writing:
Code:
var dbid = ds_list_find_value(list1, 1);
if (is_undefined(dblid)) dblid = 0;
If you do need to perform this kind of check a lot then I'd suggest writing a function:

Code:
/// list_find_alternate(list, pos, default);
var r = ds_list_find_value(argument[0], argument[1]);
if(is_undefined(r)) return argument[2];
return r;
then you can call it like so:
Code:
var dbid = list_find_alternate(list1, 1, 0);
a nice 1 liner
 

FrostyCat

Redemption Seeker
There are 3 issues with the is_undefined() solution:
  • It's possible to synthetically insert undefined into a list.
  • The Manual's entry on ds_list_find_value() states that 0 can sometimes be returned for out-of-bound entries.
  • There have been several cases in the past of crashes on isolated exports when accessing data structures beyond bounds.
If you want to genuinely check for the out-of-bounds case, I would recommend ds_list_size(). This is perfectly stable and well-defined behaviour that has never been broken in GMS 2 history, unlike checking for undefined.
Code:
var dbid = (ds_list_size(list1) <= 1) ? 0 : list1[| 1];
On a related note, this is why I also discourage the related form below on maps for checking if a key isn't in it:
Code:
// Don't do this for checking the absence of a key
if (is_undefined(map1[? "key"])) {
  ...
}
The best-practice solution is to check ds_map_exists() instead.
Code:
// Do this instead
if (!ds_map_exists(map1, "key")) {
  ...
}
 

RizbIT

Member
im trying to understand or see if using non standard (for me...) syntax in coding will make sense or things easier

for example you wrote
(is_undefined(map1[? "key"]

no what does the ? mean, why is it there, thats something id never use, however im sure it simplifies coding syntax so this is what my question ispartly about.

maybe theres a section in help file but what do i search for? 'ternary operators' ?
 
Top