Accessing script vars from code

Login to reply  Page: « < 1 of 1 > »
11 Jul 2010 - 17:282828
Accessing script vars from code
I thought I'd posted this before, but can't find it, so I apologise if this is a repost...

Sometimes, it's easier to code a solution than to script it, especially a complicated puzzle that players need to work out. This will often mean adding bespoke variables into the char_data struct, but wouldn't it be easier to simply use the script variables.

These 2 functions below allow interaction between code and script using player (or mob) script vars. Although they are specifically designed for integer variables, it wouldn't be hard to make string versions too.

Drop these into your dg_variables.c file:
int get_script_int_variable(struct char_data *ch, char *field)
{
  char str[MAX_INPUT_LENGTH];
  struct trig_var_data *vd;
  int val;

  if (SCRIPT(ch)) {
    for (vd = (SCRIPT(ch))->global_vars; vd; vd = vd->next)
      if (!str_cmp(vd->name, field))
        break;
    if (vd) {
      snprintf(str, MAX_INPUT_LENGTH, "%s", vd->value);
      val = atoi(str);
      return(val);
    }
  }
  return(0);
}

int set_script_int_variable(struct char_data *ch, char *field, int iVal)
{
  char str[MAX_INPUT_LENGTH];

  sprintf(str, "%d", iVal);

  if (SCRIPT(ch)) {
    add_var(&((SCRIPT(ch))->global_vars), field, str, GET_IDNUM(ch));
    return(iVal);
  }
  return (0);
}
Drop the prototypes into dg_scripts.h, somewhere just after this line:
/* From dg_variables.c */
Now, you can easily set or remove script vars, like these examples:
int val=1;
set_script_int_variable(ch, "test_var", 5);
set_script_int_variable(mob, "unlocked_door", val);

val = get_script_int_variable(ch, "test_var");
val = get_script_int_variable(mob, "unlocked_door");


__________________
Login to reply  Page: « < 1 of 1 > »