Comparing 2 variables in an if statement.

Posted by Zack on Thu 19 Jan 2023 06:01 AM — 5 posts, 12,910 views.

#0
Hey all,
Is it possible to have 2 variables in an if statement?
Here's what I'm trying to create.
if @steak and @chicken == "0" then
Send("cook fish")
end -- if
Trying to create an auto cooking script. It looks at my inventory, sets the amount of each type of food in their own variables. That part works fine but I'm having trouble comparing the first two to see if it should ignore them to cook the third item.

I know you can compare wild cards like on a prompt.
%1 current hp
%2 max hp.
if %1/%2 ,= .15 then
Send("cast heal")
end -- if
However I wasn't having much luck with pulling from variables outside of triggers.
Please note the prompt was just an example, the first if then is what I'm working on.
I've searched the site but can't seem to find the right phrases to find the answer.
Thanks in advance.
Australia Forum Administrator #1
Certainly you can have complex conditions in an "if".

It would look like this:


if @steak == "0" and @chicken == "0" then
  Send("cook fish")
end -- if
USA Global Moderator #2
I advise getting out of the habit of using @variables inside scripts and only using them when needed for variable match patterns. They're evaluated and replaced before the code gets sent to the script execution engine, which means that they will not pick up any changes that occur during your script. That's fine much of the time, but you will eventually run into a case where a script is broken because of this and you won't know why.

Use @variable expansion in match patterns because that's necessary for matching against variable contents, but inside your script the GetVariable function will provide more consistently sane results.
Amended on Thu 19 Jan 2023 03:29 PM by Fiendish
Australia Forum Administrator #3
Further to that, it is also preferable to convert them to numbers, particularly if you are going to compare to, say less than 1000.

So it would preferably look like:




-- convert MUSHclient variables to Lua variables
local steak   = tonumber (GetVariable ("steak")) or 0
local chicken = tonumber (GetVariable ("chicken")) or 0

-- test them
if steak == 0 and chicken == 0 then
  Send("cook fish")
end -- if


The stuff about "or 0" is to allow for if the variables don't exist at all, and give them the default values of zero.
Amended on Fri 20 Jan 2023 06:39 AM by Nick Gammon
#4
Excellent, thank you all so much for the help. I'm always looking for better ways to work within MC so will incorporate the feedback.
I've been working with GetVariable but wasn't sure if one could fit it into an if then statement. I primarily used it when doing math on variables.
I appreciate your help.
I love that the community is always helpful.
Take care all.