Function to flip boolean attributes

cfiggis
28 Jan 2020, 19:52

I'm trying to create a function that receives a parameter (an object.attribute) and flips that boolean attribute. I'm not sure how to get the syntax right.

Here's what I've got. I created a function that takes one parameter (which I've named: attrib).

And here's the script I've got right now:

if (attrib = true) {
  attrib = false
}
else {
  attrib = true
}

I am guessing I've 1) got a syntax error in this, 2) it's not substituting the parameter's reference for the parameter name, or 3) both. What have I done wrong?

Edit: I should add. The function seems to run. I attached it to a test verb and fed it an object.attribute for parameter. But the boolean doesn't flip.


mrangel
28 Jan 2020, 22:56

attrib is a local variable. It doesn't exist outside your function. Parameters in Quest are not passed by reference unless they are lists or dictionaries.

I also don't see why you would need such a function for something that you can already write in one line.

someobject.someattribute = not someobject.someattribute

If you want to set an attribute from within a function, you need two parameters: the object, and the attribute name.
Theoretically you could do something like:

<function name="FlipBoolean" parameters="obj, attr">
  set (obj, attr, not GetBoolean (obj, attr))
</function>

But to use that function, you'd be writing:

FlipBoolean (object, "myflag")

which is barely shorter than

object.myflag = not object.myflag

cfiggis
29 Jan 2020, 00:00

I keep confusing myself. Let me step back and explain the context. Perhaps you can explain the logical way to do it.

I have a box with multiple lights. The box has an attribute for each light. light_1, light_2, etc.

So I want to have a command or a verb or something where they say "toggle 1" and it toggles the attribute Box.light_1

And so I thought I'd create a function where the function handles the toggle part of it, and I pass that function the object. And based on the parameter "1" or "2" I'd change that corresponding attribute on the Box object.

Does that make sense?


mrangel
29 Jan 2020, 00:16

That makes sense.

I think the 'FlipBoolean' function I posted above looks like what you want, then. It takes two parameters; an object and an attribute name.
It uses the function GetBoolean to get the value of a boolean attribute, given the object and attribute name; the not operator turns true into false or vice versa; and set sets an attribute when given an object, attribute name, and a new value.

The first parameter is the box; the second parameter is the name of the attribute.

Or if all the lights are on the same box, you could make a function with a single parameter number.
Its script would look like:

attrib = "light_" + number
state = GetBoolean (box, attrib)
set (box, attrib, not state)

(You could shrink this down to one line, set (box, "light_"+number, not GetBoolean (box, "light_"+number)), but that's a little harder to read)