Omnimaga

Calculator Community => TI Calculators => Lua => Topic started by: Roondak on July 17, 2014, 05:38:35 pm

Title: Reducing the number of If statements
Post by: Roondak on July 17, 2014, 05:38:35 pm
So I was programming a function that looked like this:


function name(input)
    if input==1 then
        code
    elseif input==2 then
        code
    elseif input==3 then
        code
    ...
    end
end


Is there a better way to do this? Could I use some sort of table or something?
Title: Re: Reducing the number of If statements
Post by: Keoni29 on July 17, 2014, 05:39:46 pm
Depends on the "code" in between really.
Title: Re: Reducing the number of If statements
Post by: Streetwalrus on July 17, 2014, 05:40:00 pm
In lua you can put functions in a table, though a cleaner way to do that would be the "case" structure if it exists in lua.
Title: Re: Reducing the number of If statements
Post by: Roondak on July 17, 2014, 05:44:30 pm
Depends on the "code" in between really.
Here's an example from my code:

drawstr="Do you want to continue"
options={"Yes", "No"}
gamestate="choice"
timer.start(textspeed)

drawstr, options, and gamestate are all my own variables.


EDIT: I guess if I'm just assigning variables, I could have it just do that from a table.


In lua you can put functions in a table, though a cleaner way to do that would be the "case" structure if it exists in lua.
Some quick Google-Fu says that there isn't any case structure in Lua.
Title: Re: Reducing the number of If statements
Post by: bb010g on July 31, 2014, 01:16:38 pm
This may be helpful: http://lua-users.org/wiki/SwitchStatement
Title: Re: Reducing the number of If statements
Post by: Jonius7 on November 20, 2014, 04:52:55 am
I think using a table would be quite efficient, it just depends on what variables/attributes you want to use for each case (if statement).
You can also name attributes of a table as well.
Here is some random example, you can possibly use a for loop, depending on the situation.

Code: [Select]

mtable = { {id = 1, message = "This is the first one", gamestate = "Mode1"},
{id = 2, message = "This is the second one", gamestate = "Mode2"},
{id = 3, message = "This is the third one", gamestate = "Mode3"}
}

function on.paint(gc)
  for g=1, #mtable do     --up to mtable length
    gc:drawString(mtable[g].message, 10, g*20, "top")
  end
end


EDIT: Crap, over 3 month necropost!!! Just noticed.
Title: Re: Reducing the number of If statements
Post by: Happybobjr on November 20, 2014, 05:06:01 am
I could be wrong, but you might be able to do something similar to axe and do:
Code: [Select]
function name(input)
    input
    !if -1 then
        code
    else!if -1 then
        code
    else!if -1 then
        code
    ...
    end
end