How do you get the name of a value in a table

Hey! I know it may be a dumb question but I really just wanted to know how I could get the value of a variable in a table based on its name.

For example, if we have this table:

local example =
 {
    Username = "Yes", 
    Money = 10,
    Alive = true
}

print(example[Username])

EXPECTED OUPUT:

>>Yes

How would I print the username value?
Thanks.

print(example["Username"]) --> "Yes"

what’s the problem?

print(example[Username]) --> value, in this case Yes
print(Username) --> key, in this case Username
1 Like

it should be print(example.Username) not print(example[Username])
Square brackets accepts a variable or a value which is then used to index the table.

Example:

print(example["Username"])
--is the same as
print(example.Username)
--or
local var = "Username"
print(example[var])


image
I’m not sure actually

It’s because keys are strings in this case. so you need the quotes “”

1 Like

That’s a string, not a table. It looks like a JSON. Have you decoded it?

I didn’t encode it, would that still be an issue?

Didn’t work. Still returns nill when I do image

The table you are referencing is in JSON format. You need to Decode it first.

More info: https://developer.roblox.com/en-us/api-reference/function/HttpService/JSONDecode

Read this thread javascript - Difference between using bracket (`[]`) and dot (`.`) notation - Stack Overflow
Although it is talking about JS, the same principle applies to Lua

Returns nil for some reason
image
Pain.

Quick update, I think the issue is the remote events. When defining the table in the same script it tries reading it, it actually works (E.g.:image
image

But not when using it in a remote function. Any workarounds?

passing a table through a remote should still be an lua table on the other side. the only time it is in JSON format is if you actually json format the table or do anything with html service.

Nevermind, I feel incredibly stupid.

I actually modified the wrong script, and this one, encodes it into JSON.

I guess I’m terribly sorry for wasting your time.

It works now, thank you all image

2 Likes

No worries, it happens. Table management is a bit tricky and is more of an advanced subject usually.

3 Likes

You’re storing keys/fields as undeclared variables not as strings.