Jump to content

Table loop


Drakath

Recommended Posts

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

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

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 by Guest
Link to comment

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

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...