0 votes
by (700 points)

The widget in question:

<<widget addVariableToTable>><<set $args[0].pushUnique($args[1])>><</widget>>

calling the widget to push (as a unique) the "variableToAdd" into the "tableArray"

<<addVariableToTable "variableToAdd", "tableArray">>

How would i go about doing something like this?

1 Answer

+1 vote
by (44.7k points)
selected by
 
Best answer

The .pushUnique() method basically only works for pushing strings, numbers, and booleans into arrays.  It won't work as you'd expect for pushing arrays or other objects into an array, because (at least in SugarCube) all objects are normally different, even if they have the exact same values.  (There is an exception to this: if one variable is set to another object they will be equivalent only within that same passage; the next passage load event will clone them, making them different objects.)

So, assuming you aren't trying to push an object into the array, then if you want to do a .pushUnique() it makes more sense to pass the value itself and the name of the array you'd like to uniquely add it to.

For that you'd simply do this:

/* addVariableToTable: Adds a value to an array if it's not already in that array.
   Usage: <<addVariableToTable $variableToAdd "arrayName">>
   Usage: <<addVariableToTable 42 "arrayName">>
   Usage: <<addVariableToTable "example" "arrayName">>
*/
<<widget addVariableToTable>>
	<<set State.variables[$args[1]].pushUnique($args[0])>>
<</widget>>

That widget would need to be in a passage with a "widget" tag (and a "nobr" tag is also recommended to prevent extra blank lines from appearing when using the widgets in that passage).

That code uses the State.variables object to access the list of SugarCube story variables, and having the name of the variable (without the "$" in the front) as a string within brackets allows you to access that variable.  For example, "State.variables["Table"]" is the same as "$Table", "State.variables.Table", and "State.variables[$ArrName]" (if we assume $ArrName = "Table").

I should mention that the above code assumes that the second argument ($args[1]) is a valid array name (without the "$" part).  It will throw an error if you give it a name that isn't a valid array's name.

If you want to add objects uniquely into the array then it gets more complicated, since you can't use the .pushUnique() method.  If that's what you want to do, we'll need more detail about the objects.

Hope that helps!  :-)

by (700 points)
Seems to work, i didn't want to mess around with objects, just wanted to push a simple string or number into a an array with a widget :)

Thanks!
...