Calling a function that has a variable in it's name

[Sugarcube 2.36.1]

I have two functions called:


/* many more similar functions to come */

I have a variable $numCalls currently = 1;

I want code (another seperate function) that will call any function based on my $numCalls variable without using if statements or case statements as I may have many conversations. I know the solution has something to do with using State.variables I’m pretty sure. Just not sure of correct syntax.

Here’s what I’m trying inside of another function:

<<set $numCalls += 1>>
<<set _temp to State.variables["conversation"+$numCalls]>>
<<_temp>> /* I want this to call the function <<conversation2>> */

I’ve also tried

<<set $numCalls += 1>>
<<set _temp to `"conversation"+$numCalls`>>
<<_temp>> /* but conversation2 function still doesn't get called */

Thanks for any help.

Ah yes, I did something like this in my last game using what’s been called the “stupid <<print>> trick.” Which is that if you tell Sugarcube to print something and the string printed is valid Sugarcube markup, it will then also execute that markup. You don’t even need a temp variable; you can just say <<print "<<conversation" + $numCalls + ">>">>.

It feels so kludgy that I wince a little every time I do it, but it does work.


Thank you E. Joyce. You’re right, that does work! Curious if anyone else has a better solution, but I’ll use this for now. Thanks again.

1 Like

For a less kludgy solution, you can use the <jQuery>.wiki() method:

<span id="conversation"></span>

    <<run $("#conversation").wiki("<<conversation" + State.variables.numCalls + ">>")>>
1 Like

clarification: those are either Macro or Widget calls, not functions.

A function is something like hasVisited() or tags(), they may return a value, and accept values as arguments.

1 Like

What are your conversations doing? Do they need to be macros or widgets? If they could be passages, you could do <<include `"conversation" + $numCalls`>>

(edit: oops, forgot the backticks, thanks!)

1 Like

That should be

<<include `"conversation" + $numCalls`>>

with backticks to work, but yes, that seems like a more convenient way to do this.

1 Like

Yeah, sorry. They are widget calls.