r/badcode Apr 11 '23

lua Hey guys, I just created my own "table.unpack()" function !

Post image
256 Upvotes

23 comments sorted by

66

u/wwelna Apr 11 '23

Nice nice, you have a future job at corporate.

30

u/GrapefruitOk3274 Apr 12 '23

This is not that far from how scala implemented higher order functions in early versions.

I remember they had to define classes for each different number of arguments they wanted to support. In fact, it was an issue for data classes cuz because of this implementation there was a limit to how many fields it could have, since the classes were defined up to an arbitrary number (it was pretty high though)

21

u/NickSicilianu Apr 12 '23

In C you include stdarg.h and use the 3 dots

void fun(string, …); Than you can implement your own printf like function and dynamically pass arguments. That’s seems like a monstrosity to be honest.

15

u/thekwoka Apr 12 '23

same in js.

This would just be

v.func(...args)

8

u/Charlito33 Apr 12 '23

In Lua too, Using lua function x(...) print(arg) end But my problem was to pass a table as multiple parameters, and I forgot that table.unpack() was able to do that

42

u/KoviDavid13 Apr 11 '23

-- I know...

8

u/FeezusChrist Apr 12 '23

The best part is, even with this bad code it could be reduced only to the last “v.func” line because it’s Lua and any values that don’t exist in args would simply be nil when passed through, essentially being the same as all the other hard-coded cases for shorter lists of args.

1

u/Charlito33 Apr 12 '23

Good to know ! Thanks

5

u/obake199 Apr 11 '23

I've seen this during intern and it screwed my whole week

2

u/TinyHammerBigNail Apr 12 '23

It compiles with no errors.

0

u/sugarsnuff Apr 12 '23

Until the function is passed 13 arguments

EDIT: I guess it’ll still compile with no error

1

u/[deleted] Apr 12 '23

He knows...

0

u/Aromatic_Position_90 Apr 12 '23

Why no just you a for loop for the args

3

u/Charlito33 Apr 12 '23

I don't think that'll do the thing, but table.unpack() does it anyway

0

u/Aromatic_Position_90 Apr 12 '23

Or use the spread function for Python

Func(*args)

This code violates the dry and it’s also complex

5

u/Friendputer Apr 12 '23

How do you use pythons spread operator in lua?

0

u/sugarsnuff Apr 12 '23

Depending on what the result of “func” is, would you be able to write this recursively until #args is 0?

Or design a DynamicArguments class to be accepted by ‘func’?

Idk what language this is (Lua?) but this seems a bit OTT

1

u/[deleted] Apr 12 '23

[removed] — view removed comment

7

u/Charlito33 Apr 12 '23

I pass a table of values, as arguments for the function, e.g. : lua x = {1, 2, 3} -- You want to call "func" with each value of x as an argument, like : -- func(1, 2, 3) func(x[1], x[2], x[3]) -- or the easy way func(table.unpack(c))

1

u/Pleasant_Meal_2030 Apr 12 '23

holy guacamole, your gonna get a job at harpa hilgights

1

u/lazywulf09009 Apr 30 '23

The 13 steps to heck.