Drakath Posted June 8, 2014 Share Posted June 8, 2014 I have a table with some numbers: local numbers = {{1,240},{3,4670},{5,64343},{7,8704},{9,10476}} If I can retrieve numbers: 1,3,5,7,9, how can I get a number next to it? For example if I get a number 3 I want to retrieve a number 4670. Link to comment
Den. Posted June 8, 2014 Share Posted June 8, 2014 You can use the lua function unpack to return all values of a table. Following your example: local numbers = {{1,240},{3,4670},{5,64343},{7,8704},{9,10476}} for key, number in ipairs(numbers) do local first, second = unpack(number) --first and second denote to the first and second numbers in the table, so 1 and 240 respectively, etc. --An alternative method would be: local first, second = number[1], number[2] end You might also want to refer to this tutorial. Link to comment
Drakath Posted June 8, 2014 Author Share Posted June 8, 2014 I don't want to unpack the whole table. If I enter 7, I should get 8704. Link to comment
Den. Posted June 8, 2014 Share Posted June 8, 2014 (edited) Look at the tutorial, and this: 8704 is the second value, of the fourth table in numbers. numbers[4][2] -- will return 8704 in your example --If you want the key of 8704 to be 7 then you can do one the following: numbers = {[7] = 8704,...} numbers[7] = 8704 Edited June 8, 2014 by Guest Link to comment
Drakath Posted June 8, 2014 Author Share Posted June 8, 2014 Error: attempt to index field '?' (a number value) local numbers = {{1,2},{3,4},{5,6},{7,8},{9,10}} function check () local number = 3 for i,v in ipairs (numbers) do if number == v[1] then outputChatBox(v[1].." | "..v[1][2]) break end end end addCommandHandler("check", check) Link to comment
Den. Posted June 8, 2014 Share Posted June 8, 2014 Error is on line 7: v[1] refers to 1, which is inside v ( {1, 2} ), v[1][2] is trying to index 1, which is a number value. If you want the SECOND value, then use v[2], as in the following snippet: function check () local number = 3 for i,v in ipairs (numbers) do if number == v[1] then outputChatBox(v[1].." | "..v[2]) break end end end addCommandHandler("check", check) Link to comment
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now