Home > OS >  Is there an alternative to an if statement in Lua?
Is there an alternative to an if statement in Lua?

Time:04-22

I would like to know if there is a alternative to using a normal if statement in lua. For example, in java there are switch statements but I cant seem to find that in Lua

CodePudding user response:

Lua lacks a C-style switch statement.

A simple version of a switch statement can be implemented using a table to map the case value to an action. This is very efficient in Lua since tables are hashed by key value which avoids repetitive if then ... elseif ... end statements.

action = {
  [1] = function (x) print(1) end,
  [2] = function (x) z = 5 end,
  ["nop"] = function (x) print(math.random()) end,
  ["my name"] = function (x) print("fred") end,
}

CodePudding user response:

The frequently used pattern

local var; if condition then var = x else var = y end

can be shortened using an and-or "ternary" substitute if x is truthy:

local var = condition and x or y

CodePudding user response:

if test == nil or test == false then return 0xBADEAFFE else return test end

Can be shorten up to...

return test or 0xBADEAFFEE
  • Related