CassioTDS
(BayerischerPartei)
November 10, 2021, 11:52pm
#1
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.
batteryday
(batteryday)
November 10, 2021, 11:55pm
#2
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
Prototrode
(Nachiyen)
November 10, 2021, 11:57pm
#4
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])
Dev_Ryan
(Dev_Ryan)
November 10, 2021, 11:58pm
#6
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?
CassioTDS
(BayerischerPartei)
November 10, 2021, 11:59pm
#8
I didn’t encode it, would that still be an issue?
CassioTDS
(BayerischerPartei)
November 11, 2021, 12:00am
#9
Didn’t work. Still returns nill when I do
Dev_Ryan
(Dev_Ryan)
November 11, 2021, 12:00am
#10
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
Prototrode
(Nachiyen)
November 11, 2021, 12:01am
#11
CassioTDS
(BayerischerPartei)
November 11, 2021, 12:02am
#12
Returns nil for some reason
Pain.
CassioTDS
(BayerischerPartei)
November 11, 2021, 12:04am
#13
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.:
But not when using it in a remote function. Any workarounds?
Dev_Ryan
(Dev_Ryan)
November 11, 2021, 12:05am
#14
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.
CassioTDS
(BayerischerPartei)
November 11, 2021, 12:06am
#15
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
1 Like
Dev_Ryan
(Dev_Ryan)
November 11, 2021, 12:08am
#16
No worries, it happens. Table management is a bit tricky and is more of an advanced subject usually.
2 Likes
You’re storing keys/fields as undeclared variables not as strings.