Lua:我需要在if中重复变量吗?

Joh*_*Big 2 lua

当我说 if var == "one" or var == "two" or var == "three" or var == "four" then 并且var总是相同时,我可以以某种方式缩短它吗? if var == "one" or "two" or "three" or"four" then

我必须使用括号吗?

Jas*_*ijn 5

我们可以利用表格。特别是,如果some_table 包含some_key,则some_table[some_key]返回nil,这是错误的。

例如:

if ({one=1, two=1, three=1, four=1})[var] then
Run Code Online (Sandbox Code Playgroud)

我使用它是1因为它的输入时间很短,但是您可以使用除nil或 之外的任何值false,因为这两个是 Lua 中唯一的假值。

每次评估条件时都会创建一个新表,因此如果您想频繁检查它(例如在紧密循环中),则在循环创建表可能是值得的:

local CONDITION = {one=1, two=1, three=1, four=1}
...
   -- inside a loop:
   if CONDITION[var] then
Run Code Online (Sandbox Code Playgroud)