1

i need help, about how to replace my array2d with another array1d

example array2d, that i have

role = {{"mike", "30", "1"},
        {"mike", "50", "3"}}

i want to replace the third array value "role[...][3]" with this array1d

role_listname = {
    [1] = "Winner!",
    [2] = "Funnier!",
    [3] = "Crazy!"
}

so the result i got.

1. Winner - 30p
2. Crazy - 50p
Not like
1. Winner - 30p
2. Funnier - 40p

my code :

for i = 1, #role do
    role[i][3] = role_listname[i]
    print(i .. ". " .. role[i][3] .. " - " .. role[i][2])
end

i don't know. it's not working, could you tell me how it's work ?

2
  • I'm not sure what you want to do, but your role_listname table looks definately wrong. You are using strings ("1", "2", etc) as keys, but in your for loop you use numeric values (1, 2, etc). This makes a difference! Commented Nov 9, 2016 at 23:22
  • oh yeah,i forgot about that. edited now Commented Nov 9, 2016 at 23:26

1 Answer 1

1

You logic is wrong. You are using the loop variable i as index, but you want to use the corresponding entry in the role table:

role = {
    {"mike", "30", 1},
    {"mike", "50", 3}
}
role_listname = {
    [1] = "Winner!",
    [2] = "Funnier!",
    [3] = "Crazy!"
}

for i = 1, #role do
    role[i][3] = role_listname[role[i][3]] -- here is the change
    print(i .. ". " .. role[i][3] .. " - " .. role[i][2])
end

Note that i also switched the indices in the role table to numerics. But this does not really matter, you could use any keys. They just have to match with the corresponding keys in the role_listname table.

Sign up to request clarification or add additional context in comments.

1 Comment

what a shame, sorry for my logic, btw, i am still learning. but thank's for help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.