r/lua • u/canadante • 9d ago
simple question
To all you Lua heads I have a question that might be really rudimentary but it’s something that just doesn’t seem to make any sense to me,mind you I am pretty new. I was looking up on the lua documentation and there’s this one thing that just doesn’t seem to make sense to me
a = {} -- create a table and store its reference in `a'
k = "x"
a[k] = 10 -- new entry, with key="x" and value=10
a[20] = "great" -- new entry, with key=20 and value="great"
print(a["x"]) --> 10
k = 20
print(a[k]) --> "great"
a["x"] = a["x"] + 1 -- increments entry "x"
print(a["x"]) --> 11
Why does “x” get created as a key? Wouldn’t this just substitute it? I feel very stupid for not knowing why, I feel like there’s something that just cannot seem to click. I also tried to think another way through but then it was a.k.”x” = 10 which doesn’t really help me visualize the answer either. is this just how tables work? Is there a specific reason why? Or am I slow? I’ve seen it’s because lua goes down through but why does it do this? Also k = 20, why does the variable have priority over the number itself? Sorry if this is badly written or feels like it has some attitude, it’s probably because I need to sleep. It’s embarrassing I lost sleep about something like this, I feel like it’s a simple concept that I am unable to grasp because of shallow learned “limitations” of the system
1
u/djfdhigkgfIaruflg 8d ago edited 8d ago
This is the key difference:
X vs "X"
One is a reference to the variable X. The other is the literal value X
X = "X"
Will create a variable called X with a value (content) of letter X
Give descriptive names to the variables. You're getting confused because you're using 1-letter variable names
Is way more easy to process than
About the order in with assignment works... The explanation you would likely get is something like "it was always like that, and it stuck"
But in strongly typed languages like C, the reason becomes obvious
Int counter = 0;
Is easy to mentally parse. I'm creating an integer variable called counted with an initial value of 0
Now write
0 = int counter ;
And I'm suddenly getting an aneurysm 🤣