lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'd write:
local foo = t.foo; if not foo then foo = whatever; t.foo = foo end // Lua
(i.e. first assign the local, to reassign this local to the t field).

If you don't need to assign t.foo itself, you can of course write:
  local foo = t.foo or whatever; // Lua

In C, I'd use chained assignements:
  /*auto or register*/ Object *foo = t.foo = t.foo || whatever; // C

Stricter variant _javascript_/Java/C#/C++ (if the || operator is overloaded or only returns a boolean):
  /*local or var*/ foo = t.foo = (t.foo == null ) && t.foo || whatever; // _javascript_
  Object foo = t.foo = (t.foo == null ) && t.foo || whatever; // Java
   /*auto or register*/  Object *foo = t.foo = (t.foo == null ) && t.foo || whatever; // C++

But Lua still does not like chained assignments in expressions (only supports assignments as separate instructions).


Le dim. 5 mai 2019 à 06:50, Sam Pagenkopf <ssaammp@gmail.com> a écrit :
have you benchmarked it?

also note that "if not x then x = y" can be written as "x = x or y"

On Sat, May 4, 2019 at 10:05 PM Soni "They/Them" L. <fakedme@gmail.com> wrote:
I often write code like:

local foo = t.foo
if not foo then foo = whatever t.foo = foo end
-- use foo here

but ideally I'd like to write it like:

if not t.foo then t.foo = whatever end
local foo = t.foo

and still have the same performance (or better).

does lua do any optimizations related to this?