像布尔值一样在两个字符串之间进行切换

我经常得到一些具有代表非布尔状态的变量的对象,并希望尽可能简单地切换它们。

function switch_state()

  if foo == "abc" then
    foo = "xyz"

  else
    foo = "abc"

  end

end

我能否缩短代码呢? 与以下代码类似的任何内容都可以

foo = not foo

我的第一次尝试是

foo = (foo and not "abc") or "xyz"

但是,这当然不起作用 =(

点赞
用户234175
用户234175

你可以使用表作为状态转移图:

function switch_state()
  local transit = { abc = "xyz", xyz = "abc" }
  foo = transit[foo]
  return foo
end
2015-02-18 12:58:26
用户1514861
用户1514861

一种方法是这样做:

foo = (foo == "abc") and "xyz" or "abc"

2015-02-18 12:59:41
用户2726734
用户2726734

另一种方法是:

foo 存储为布尔值,并使用 foo = not foo 进行切换。

当需要字符串时,使用 foo and "abc" or "xyz"

function toggle_state()
  foo = not foo
end

function state()
   return foo and "abc" or "xyz"
end
2015-02-18 13:12:49