Function help

Post Reply
tarrant
Posts: 49
Joined: Thu Apr 15, 2010 10:36 pm

Function help

Post by tarrant »

Code: [show] | [select all] lua
function lootSwitch()
        if loot = "On" then
                loot = "Off";
        else
                loot = "On";
        end
end
Hi all, the above function gives the error below. I'm not too sure what's wrong because i already have the 'then' that's expected there. Or am i doing something wrong?
Lua syntax error:[string "function lootSwitch()..."]:2: 'then' expected near '='
Also, when should i use a single =, and double ==?

I'm still pretty new to this. Thanks for your patience and help.

User avatar
Omit
Posts: 190
Joined: Sun Aug 01, 2010 10:54 pm
Location: Middle Earth
Contact:

Re: Function help

Post by Omit »

Try
if loot == "On" then

I can't tell you the number of times I have done this.
(Use the == anytime you are comparing 2 values, use = to set values)

Iocun
Posts: 174
Joined: Wed Dec 02, 2009 1:45 am

Re: Function help

Post by Iocun »

You may also want to consider changing the strings "On" and "Off" to the boolean values true and false. It won't generally make a huge difference (except for slightly simplifying certain constructs and, I suppose (?), a tiny advantage in processing time), but it just seems like good practice to me to use all data types exactly for what they were meant for. Two-state variables of the type on/off, yes/no, correct/incorrect, existent/non-existent and so on, are all archetypical examples of boolean toggles, so I'd generally use true/false for those.

(I know other people have other preferences there though and like using strings or numbers for some of those.)

Written with booleans, your function would become:
Code: [show] | [select all] lua
function lootSwitch()
        if loot then
                loot = false
        else
                loot = true
        end
end
You see that using booleans will also shorten/simplify the if statement slightly. It also has the advantage that it lessens the risk of errors due to typos: If, in your original script you accidentally used "on" instead of "On" somewhere, it would produce unexpected results, since Lua is case-sensitive.

Yetzederixx
Posts: 186
Joined: Sun Nov 14, 2010 5:57 am

Re: Function help

Post by Yetzederixx »

Remember that in Lua, unlike Java or C(++), 0 will register as true if you test it by itself.
Code: [show] | [select all] lua
x = 0
-- will always echo true
if (x) then echo("True") else echo("False") end
So be wary using integral values for true/false

tarrant
Posts: 49
Joined: Thu Apr 15, 2010 10:36 pm

Re: Function help

Post by tarrant »

Thanks guys. worked very well.

Post Reply