Yuescript icon indicating copy to clipboard operation
Yuescript copied to clipboard

About new table appending idiom

Open thesolitudeofnoblesoul opened this issue 3 years ago • 7 comments

It help will help me reduce a lot of typing and typo error. But I sometime use lua with other language like C# that count not from 1 but from 0. When create table that map with C# data with would be difficult with current idiom. If idiom can be change for handle that case it would be great.

I think change to something like this would be better, handle more cases, more readable and distinguishable code. EX:

items #+= obj -- compile to: items[#items+1] = obj
items #= obj -- compile to: items[#items] = obj
items #-= obj -- compile to: items[#items-1] = obj

Thanks and regards!

thesolitudeofnoblesoul avatar Feb 11 '22 04:02 thesolitudeofnoblesoul

Just thought of adding the syntax for the common use of Lua table. When it comes to the binding frameworks there will sure be various cases that can hardly be met by a fixed set of syntax. I had thought about transforming the tb #= 1 to table.insert(tb, 1) instead of tb[#tb + 1] = 1 and they have mostly the same function, and being both the ways to append item to a Lua table. But I ended up choosing tb[#tb + 1] = 1 which is a built-in Lua syntax and has better performance.

pigpigyyy avatar Feb 11 '22 07:02 pigpigyyy

I think the item[]=value syntax (similar to PHP idiom) would be better in this case (or alias for #=). # already has many rules in Yue and can be confused with length op too.

aergo20 avatar Feb 12 '22 19:02 aergo20

Changed the table appending syntax to list[] = item instead of list #= item for better readability.

pigpigyyy avatar Feb 14 '22 07:02 pigpigyyy

Late reply but I'm surprised that << operator is not taken consideration. afaik it's not reserved in yue yet and also it's a familiar appending syntax from Ruby and C++.

like so in Ruby:

test = [3, 5, 7]
test << 9

nikneym avatar Feb 19 '22 22:02 nikneym

Lua 5.3 adds bitwise operators, maybe it’s better not to add <<.

vendethiel avatar Feb 20 '22 00:02 vendethiel

I'm probably missing something but why not just use += to append?

ChildishGiant avatar Mar 13 '22 21:03 ChildishGiant

I'm probably missing something but why not just use += to append?

"+=" is not a good idea, because you can overload operator "+" in Lua.

add = (other)=> {
  x: @x + other.x
  y: @y + other.y
  :add#
}

Vec2 = (x, y)-> :x, :y, :add#

v = Vec2 1, 2
v += Vec2 3, 4 -- here "+=" is a overloaded function from Lua table
print v.x, v.y
-- output 4 6

And you can just implement the table appending of "+=" with only Lua operator overloading functions.

add = (item)=>
  @[#@ + 1] = item
  @

tb = :add#
tb += 1
tb += 2
tb += 3
print i for i in *tb
-- output 1 2 3

pigpigyyy avatar Mar 14 '22 02:03 pigpigyyy