lua-users home
lua-l archive

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


On Thu, Jun 3, 2021 at 12:21 PM Lorenzo Donati wrote:
IMO syntactic sugar is really useful if:
1.
- It captures very common patterns, thus allowing *substantially*
reducing *complex* (i.e. difficult to read/understand at a glance)
boilerplate code.
2.
- It is expressed in a non-confusing syntax that minimizes the risks of
ambiguities.
3.
- It is general enough to be widely applicable in many contexts with the
same semantics.
4.
- It doesn't obscures fundamental language concepts.


Interesting set of rules!
Let's see whether each sugar existing currently in Lua complies with these rules.
("LR" below is the abbreviation for "Lorenzo's Rule")


o:m()     -- sugar
o.m(o)    -- meaning
LR1: yes
LR2: no   -- confusing syntax: a dot and a colon are easy to confuse
LR3: no   -- not applicable in a similar context: f=o:m
LR4: no   -- fundamental concept is obscured: object is always passed as argument into method

t.name    -- sugar
t["name"] -- meaning
LR1: yes
LR2: yes
LR3: yes
LR4: no   -- fundamental concept is obscured: member/method is just a field in a table

t={a, b=2}       -- sugar
t={[1]=a, b=2}   -- meaning
LR1: yes
LR2: no   -- confusing syntax: sometimes treated as {a=nil, b=2} by newbies
LR3: yes
LR4: yes

global       -- sugar
_ENV.global  -- meaning
LR1: yes
LR2: no   -- confusing syntax: often unclear whether variable is local or global
LR3: no   -- not applicable if global was accidentally shadowed by a local defined 100+ lines above
LR4: no   -- fundamental concept is obscured: global variable is just a field in the globals table

f"abc"    -- sugar
f("abc")  -- meaning
LR1: no   -- the sole benefit is the economy of two parentheses
LR2: yes
LR3: yes
LR4: yes

function f() end    -- sugar
f = function() end  -- meaning
LR1: yes
LR2: yes
LR3: no   -- syntax is not applicable when defining table fields
LR4: no   -- fundamental concept is obscured: function is a value

local function f() end      -- sugar
local f; function f() end   -- meaning
local f = function f() end  -- incorrect meaning
LR1: yes
LR2: no   -- confusing syntax: "meaning" vs "incorrect meaning"
LR3: yes
LR4: no   -- fundamental concept is obscured: local function is a visible upvalue for its body



As you see, each Lua sugar disobeys some of your rules.
Does this mean that each existing Lua sugar is not "really useful"?

Lua (as any other language) is a set of trade-offs.
IMO, your rules are correct in general, but too idealistic for the real world.