lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 15 April 2013 13:19, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2013/4/15 Chris Datfung <chris.datfung@gmail.com>:
>
>> Thanks. In this case, I'm stuck with Lua 5.1, is there anything comparable
>> to goto in 5.1?
>
> No. You could make a function of the whole thing and say 'return "Blue"'
> instead of 'Decision="Blue"'. But here's a neater solution.
>
> function chosen(x) return tonumber(ChooseSetting(x)) end

A common slip, especially when we're switching back and forth from
C... Remember that 0 is true in Lua. To match the original code, this
should be:

local function choose(x)
   return tonumber(ChooseSetting(x)) > 0
end

> Decision = (chosen(a) and chosen(b) and chosen(c) and "Blue")
>         or (chosen(d) and chosen(e) and "Red")
>         or (chosen(f) and "Yellow") or "Orange

If that looks too cluttered (and it probably will, if your actual code
doesn't use tests that look all the same like this example), the code
below (which implements Dirk's first suggestion) will work just as
well:

local function decide(a, b, c, d, e, f)
   if choose(a) and choose(b) and choose(c) then
      return "Blue"
   end
   if choose(d) and choose(e) then
      return "Red"
   end
   if choose(f) then
      return "Yellow"
   end
   return "Orange"
end

local Decision = decide(a, b, c, d, e, f)

-- Hisham
http://hisham.hm/