Expressions As Statements

lua-users home
wiki

In some languages, various common idioms are made possible by the allowance of expressions to be used as statements. A Perl example:

f() or die("fail");   # short alternative to unless (f()) { die("fail"); }

In Lua, this does not work since expressions cannot be used as statements:

f() or error("fail")  -- syntax error

Lua chooses this behavior to avoid ambiguities in the language.

a = b - c
-- Could this be "a = b; -c;"?
a = b
-c
-- Could this be "a = b - c"?

Still, there may be some ways to achieve a similar effect in Lua:

-- method #1
local _ = f() or error("fail")

-- method #2
local function E() end
E(f() or error("fail"))

-- method #3
-- This is not much better than if not f() then error("fail") end
if f() or error("fail") then end

In method #1, the result is assigned to a variable named "_" that is not used. The name "_" has no special meaning to Lua, and we could choose any other name, but _ is conventionally used when we want to ignore a value as in the idiom below, so this choice makes semantic sense.

for _,v in ipairs(t) do print(v) end

Even though it goes against the terseness we desire, the local keyword is added to limit the scope and avoid and global variable side effect (local is implicit in the for loop variables above).

Another possiblility (--RiciLake) is

(f or Nil)()  -- similar to f and f() as well as if f then f() end

Here's another pathological workaround by RiciLake [1]:

repeat until nsfm:fileExistsAtPath(testfile)
   or Shriek "File doesn't exist"

The Perl-like syntax can be added in Metalua--see "Expressions as Statements" in MetaLuaRecipes:

-{ extension 'expressionstatements' }
f() or error 'failed!'

See Also


RecentChanges · preferences
edit · history
Last edited March 19, 2009 1:25 pm GMT (diff)