Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Is there object destructuring in Lua? [Quick question]

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'}

3 comments

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)

0

Oh, sorry I didn't know putting my real name is against the rules, I just couldn't thing of anything else :P

0

also it's giving me nil, unless it's an array

2 answers

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 :)

1 comment

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

Not sure if this is correct, but you could do

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

1 comment

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

This discussion is preserved as it was. New answers, comments, and votes are closed.