Jump to content

table question


xTravax

Recommended Posts

hello umm

if i had something like this

  
playerData = { 
{1,20}, 
{2,40}, 
{3,60}, 
{4,80}, 
{5,100} 
} 
  
function testFunction(thePlayer,commandName,id) 
for index,pdata in ipairs(playerData) do 
if id then 
-- give money depending on id(1,2,3,4 or 5) 
else outputChatBox("id required!") return end 
end 
end 
addCommandHandler("mooney",testFunction) 
  

this is just an example.

how could i make it that when i write /mooney 3 that it automatically finds the 2nd value in table which is 60 and gives me 60 dollars?

Link to comment
  
  
playerData = { 
    {1,20}, 
    {2,40}, 
    {3,60}, 
    {4,80}, 
    {5,100} 
} 
  
function testFunction(thePlayer,commandName,id) 
    if tonumber(tostring(id)) then 
        local attempts = 0   
        for index, pdata in ipairs(playerData) do 
            if pdata[1] == id then 
                if attempts >= #playerData then 
                    return outputChatBox("The ID doesn't exist!", thePlayer) 
                    break 
                end 
                givePlayerMoney(thePlayer, pdata[2]) 
                return true 
                break 
            else 
                attempts = attempts+1 
            end 
        end 
    else  
        return outputChatBox("Invalid ID provided!", thePlayer)  
    end 
end 
addCommandHandler("mooney",testFunction) 
  

Link to comment

What's the point of an ID within a table as the value? Why not just:

local playerData = { 
    20, -- [1] = 20 
    40, -- [2] = 40 
    60, -- [3] = 60 
    80, -- [4] = 80 
    100 -- [5] = 100 
} 

And then remove the loop and simply use playerData[id]. Or if that data is static, you can just multiply the id by 20 (20 * 1 = 20, 20 * 2 = 40, 20 * 3 = 60, 20 * 4 = 80, 20 * 5 = 100).

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...