how can I get the value of a dictionary with a number position
I have tried this but it I get an error
local Dictionary = {
name1 = "joe",
name2 = "mark",
}
print(Dictionary [1]) ----does not print joe I get error
how can I get the value of a dictionary with a number position
I have tried this but it I get an error
local Dictionary = {
name1 = "joe",
name2 = "mark",
}
print(Dictionary [1]) ----does not print joe I get error
It’s been defined under name1
, so you need to do Dictionary.name1
calling it by (Dictionary [1])
will work if you don’t put the value under a variable, such as :
local Dictionary = {"joe","mark"}
print(Dictionary[1]) ---- get joe
You are using a dictionary, so you must use strings as the element name
print(Dictionary ["name1"])
Also you must format the dictionary like this:
local Dictionary = {
["name1"] = "joe",
["name2"] = "mark",
}
Whats the difference from [“name1”] and name1?
Incorrect, a.b is syntax sugar for a[“b”] so same exact thing.
only difference would be that you can include special characters,
such as spaces ["My cool Item"]
Hmm, it seems to be throwing an error when I tested it…
Lemme try again
Edit:
Actually yeah I forgot to put an end.
the error says you forgot an end…
Simple fix, just do:
print(Dictionary.name1)
There’s not really much of a difference aside from readability.
Not correct either, sorry, you can do .name1 as well.
dict = {
name1 = "sup bro"
}
name1 = "hi"
print(dict.name1)
It doesn’t grab a variable, just a table field
But you could do this
dict = {
[name1] = "sup brooooo"
}
print(dict.hi)
Now THAT uses the variable value.
You cant index a dictionary by position, but if you want a REALLY hacky way of doing this which I do not recommend:
function FindPosInDict (dict, pos)
local Keys = {};
for Key, Value in pairs(dict) do
table.insert(Keys, Key);
end
return dict[Keys[pos]];
end
How i recommend doing this in your situation is to format your dictionary like this:
local Array = {
{
["name"] = "joe"
},
{
["name"] = "mark"
}
}
print(Array[1].name) --//Prints 'joe'
If you wanted to do something like that I would recommend creating the Keys
table only for the first time, when a new index in the dictionary is created or when something is removed from the dictionary so that for a given index its corresponding reference is set to nil. This can be achieved using metatables. It’s more complicated but more efficient.
If you’re storing not references but variables of value type then you would also have to reload the Keys
table when you change a value in the table.
In the end it all depends on what you are going to use that table for, because in some cases when you don’t use that indexing by integer a lot but write to the table very often then it is not efficient to do it my way. However my solution works great when you create a table once, add something rarely but read a lot from it using these integer indexes.