Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Is there object destructuring in Lua? [Quick question]

Asked by 2 years ago
Edited 2 years ago

I dealt with many programming languages before and in almost all of them we had the concept of object/array destructuring which saves me tons of time and lines fo code, if you don't know what this is then basically say i have object

local obj = {
    name = 'something',
    lastName = 'somethingElseMaybe',
}

now I want to take out first and last name in a separate variables

local name = obj.name
local lastName = obj.lastName

But with object destructuring I could simply do

local {name, lastName} = obj // This is javascript syntax, kinda

so I was just wondering, is this concept found in Lua too?

**** I NEED TO EMPHASIZE THAT ****

in other programming languages when I try to destructure an object they don't look at the order, so in the example I put above in javascript syntax name, lastName isn't following a specific order, instead javascript looks at the matching keys for those varaible names and ten assign the value of that key to the matching variable NOT CARING ABOUT IF IT MATCHES THE ORDER OR NOT, it only cares about the order when it's an array {'Name', 'lastName'}

0
okay, im editing this since that looks like your real name. Use unpack if you want them as separate objects. local name, lastname = unpack(obj) greatneil80 2647 — 2y
0
Oh, sorry I didn't know putting my real name is against the rules, I just couldn't thing of anything else :P zeyadtota3 7 — 2y
0
also it's giving me nil, unless it's an array zeyadtota3 7 — 2y

2 answers

Log in to vote
0
Answered by 2 years ago

The correct syntax for destructuring is:

local array = {1, 2, 3, 4}
local a, b, c, d = table.unpack(arr)
print(a)
print(b)
print(c)
print(d)

I hope this solves your query :)

0
ya, table.unpack is equivelant to ... operator in javascript, I already knew it but thanks alot for helping :D I was talking about objects here in which were table.unpack doesn't work zeyadtota3 7 — 2y
Ad
Log in to vote
-2
Answered by
Neatwyy 123
2 years ago

Not sure if this is correct, but you could do

local obj = {
    name = 'something',
    lastName = 'somethingElseMaybe',
}
local name, lastName = obj.name, obj.lastName
0
Thank you so much for trying to help, but unfortunately this isn't quit what I wanted, and I don't think object destructuring is a thing in Lua :( now I understand why roblox developers don't like to use variables that much zeyadtota3 7 — 2y

Answer this question