I think I know what keys in Lua but I am not sure if it is correct.
Keys are just “indexes” for dictionaries.
local dictionary = {
key = value
}
--key would be something like an index for a dictionary
Not sure how to properly explain this.
You can access them by doing:
Dictionary[keyName] --returns the value for that key
So If I loop through a dictionary “i” is the key and “v” is the value?
Keys are how you reference data in a table. In an array, the key is just what place that value is in the table.
local names = {"John", "Lucy", "Kevin", "Bob"}
--Keys are 1,2,3,4
print(names[2]) --> Lucy
In a dictionary, the keys are the first value.
local levels = {
["John"] = 5,
["Lucy"] = 10,
["Kevin"] = 2,
["Bob"] = 1
}
--Keys are John, Lucy, Kevin, Bob
print(levels["John"]) --> 5
That is correct.
For example if you take a book, any book you want, then for example its page numbers are keys for that book’s pages. Page number 13 - key 13 refers to some page that indeed has a number 13.
So in programming languages and specifically in Lua - tables are indexed by keys. These can be numbers or other objects such as strings, other tables or even models from your game.
A table holds values that you can only extract using a key that is assigned to them (or iterators that iterate through a table).
Example:
table_example = {
[1] = "value1",
["hello"] = "value2"
}
To get “value1” you need to use key 1
table_example[1] -- gives you "value1"
To get “value2” you need to use key “hello”
table_example["hello"] -- gives you "value2"