how do i target nonlinear values in a table in loops?
values={ v1=1, v2=2, v3=3 } |
yes i know about
pairs(tbl) |
but i don't know how to use it in this context.
any help would be greatly appreciated.
thanks!



Consider the following code:
values={ v1=1, v2=2, v3=3 } cls() for k,v in pairs(values) do print(k) print(v) print("---") end |
If you run it, you get this:

What's happening here is that takes each entry in values and turns it into a pair of variables. The variable k will hold the key ("v1", "v2", etc.) and v will hold the value of that entry (1, 2, etc.). So it loops through each entry, assigning the key and value of that entry to the variables k and v each time through the loop. It's common to use the variables "k" and "v" for these kinds of loops because they stand for "key" and "value", but you could use any two variables, like "name" and "amount", or whatever you want.
But I want you to notice something important in the screenshot... just because you added them to values in the order of v1, v2, v3, that doesn't necessarily mean they are stored in that order! Notice in the screenshot that when it goes through all the entries in values, it didn't necessarily use the order you stored them in. That's important to remember. Most of the time it doesn't actually matter, but you should know it's happening that way anyway.



wait nvm i thought of somthing i used this config table and i wanted to edit it in runtime with a menu, but i can just load it to the table from a normal array :/



I should also mention, you can get back a particular named value in a table by using that name inside square brackets, like this:
values={ v1=1, v2=2, v3=3 } print(values["v1"]) |
Notice that inside the square brackets, you have to use quotes around the name. If you want to make it a bit cleaner and use dots instead of quotes, you can make your table like this instead:
values={} values.v1 = 1 values.v2 = 2 values.v3 = 3 print(values.v1) |
Hope that helps!



oh wait really? i thought that it didn't work with strings in the list.value thing! :)
[Please log in to post a comment]