如何将此简化?

我认为有一种更好的方式来写这个但我记不清了。

在 Lua 中有更好的方式来写这个吗?

if curSwitch == "shapes" then
  curSwitch = "colors"
elseif curSwitch == "colors" then
  curSwitch = "shapes"
end
点赞
用户6166627
用户6166627

通常,对于一个触发器,您可以使用XOR操作。

例如,无论B0还是1,当计算1 XOR B时,它都会倒转B

1 XOR 1 = 0; 1 XOR 0 = 1

您可能可以使用整数(理想情况下是bit)和字符串创建一个map,并在其中放置{0:“形状”;1:“颜色”},然后使用该数字进行操作。

或者,您可以仅使用true/false对于curSwitch,然后它将显示为(三元运算符):

`` ` curSwitch? "形状":“颜色”

`` `

但是如果您到处重复这个过程,那就不太好了。

祝你好运! :)

2017-08-27 11:39:03
用户7504558
用户7504558

只有当可能有两个值时才起作用:

curSwitch = (curSwitch == "shapes") and "colors" or "shapes"
2017-08-27 12:02:24
用户1944004
用户1944004

你可以使用表格来实现这样一个简单的开关。

switch = { shapes = "colors", colors = "shapes" }

curSwitch = "colors"
curSwitch = switch[curSwitch]
print(curSwitch) -- "shapes"

问题在于,如果表格中不存在该键,那么你将只能得到nil

curSwitch = "garbage"
curSwitch = switch[curSwitch]
print(curSwitch) -- nil

可以通过重载__index元方法来解决这个问题,在缺少键的情况下触发错误。

m = {
   __index = function(t,k)
      local v = rawget(t,k) or error("No such switch!")
      return v
   end
}

setmetatable(switch, m)
curSwitch = "garbage"
curSwitch = switch[curSwitch]
print(curSwitch) -- error!
2017-08-28 00:14:18
用户107090
用户107090

如何试试这样的写法。

起始代码如下:

oldSwitch = "colors"
curSwitch = "shapes"

然后使用下面的代码来切换开关:

curSwitch, oldSwitch = oldSwitch, curSwitch
2017-08-28 13:57:19