简体   繁体   中英

How do you write this shorter?

I thought there was and better nice way to write this but I can't remember.
Is there an nicer way to write this in Lua?

if curSwitch == "shapes" then
  curSwitch = "colors"
elseif curSwitch == "colors" then
  curSwitch = "shapes"
end

仅在可能的2个值下起作用:

curSwitch = (curSwitch =="shapes") and "colors" or "shapes"

How about this. Start with

oldSwitch = "colors" 
curSwitch = "shapes"

Then flip the switch with

curSwitch, oldSwitch = oldSwitch, curSwitch

Note, I don't know Lua .

Usually, for a trigger, you use XOR operation.

Like, whatever B has ( 0 or 1 ), when you calculate 1 XOR B it will invert the B .

1 XOR 1 = 0; 1 XOR 0 = 1 1 XOR 1 = 0; 1 XOR 0 = 1 .

You probably can create a map with integer (ideally, a bit ) and string and put there {0:"shapes"; 1:"colors"} {0:"shapes"; 1:"colors"} and then work with the number.

Or, you could just use a true/false for the curSwitch , then it'll look like this (ternary op):

curSwitch ? "shapes" : "colors"

But that's not that fancy if you repeat that everywhere.

Good luck! :)

You can implement such a simple switch using a table.

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

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

The problem is that if the value does not exist in the table you simply get nil .

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

This can be remedied by an overloaded __index metamethod which triggers an error in the case of absent keys.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM