Terra tuples do not destruct in Lua code
renatoathaydes opened this issue · comments
I am not sure if this is intended, but I find it a bit surprising.
Take this Lua code, for example:
> function lua2()
>> return 'ab', 'cd'
>> end
> x,y = lua2()
> =x
ab
> =y
cd
Pretty obvious.
But Terra functions returning multiple values do not work the same:
> terra point()
>> return 1,2
>> end
> x, y = point()
> =x
cdata<struct _int32_int32_>: 0x0e3ccae8
> =y
nil
The tuple is returned as the first variable, and the second is not assigned anything, unlike in Lua.
I know that I can get the tuple members like this:
> =x._0
1
> =x._1
2
But this feels a little bit lacking... What do you think, shouldn't Terra do the "destructuring" when taking a tuple from Terra code to Lua?
BTW this works fine from Terra:
> terra point()
>> return 1,2
>> end
> terra p1()
>> var x,y = point()
>> return x
>> end
> =p1()
1
I think what you want is unpacktuple
:
> terra point() return 1, 2 end
> x,y = unpacktuple(point())
> print(x, y)
1 2
I'll leave the language design question to the reader, but I don't see a way to change this without breaking backwards compatibility, so I think that discussion is entirely speculative at this point (though I'm happy to say more if you want).
I just found out that Lua 5.2 has table.pack
and table.unpack
. Would it be possible to add a similar counterpart to terralib.unpacktuple
, terralib.packtuple
?
If I understand correctly, table.pack(...)
and table.unpack(t)
are just new names for {...}
and unpack(t)
which exist in Lua 5.1 (and prior).
In Terra, you can either {...}
to create a tuple, or return ...
to create one implicitly.
> terra f() return 1, 2, 3 end
> f()
> =f()
cdata<struct _int32_int32_int32_>: 0x15659ba0
> terra g() return [{1, 2, 3}] end
> =g()
cdata<struct _int32_int32_int32_>: 0x1563ad90
> terra h() return {[{1, 2, 3}]} end
> =h()
cdata<struct _int32_int32_int32_>: 0x155db828
So I guess there are two things here: the explicit / symmetric syntax for pack
, and the fully-qualified name under terralib.*
.
Am I understanding what you're asking for?
I was just unhappy about Terra not having the same symmetric functions as Lua. I spent quite some time trying to figure out why I couldn't get multiple values back from Terra (because Terra returns a single tuple to Lua), which you told me I could fix by using terralib.unpacktuple
... then of course, the very next thing I needed was to pack them back :D but thinking about it, we can't send a "repacked" tuple from Lua to Terra, right? At least, IIUC, the Terra program, when compiled, should not be invoking Lua functions directly... anyway, I am still figuring out lots of things so I may lack the context... I think I understand now why there's no need for this in Terra, so I am closing the issue.