1

how can I use "for k, j in pairs() do" for 2 arrays in lua?

 local blipmarker1 = {
      { x = 10 , y = 5, z = 3 },
      { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
      { x = 100, y= 150, z=30 }
}
function createtext(){
    local pos = GetEntityCoords(PlayerPedId(), true)
    for k, j in pairs(blipmarker1,blimarker2) do
        draw3DText(pos.x, pos.y, pos.z, j.x, j.y, j.z)
    end
 }    
2
  • You can use a while loop and next to move through 2 arrays together. But i am unsure how the code in you post is expected to behave. Does the loop only run once? because blipmarker2 only has 1 value or does it run twice because blipmarker1 has 2 values and during the second loop blipmarker2 is nil Commented Feb 18, 2020 at 19:45
  • 3
    for _, bm in ipairs{blipmarker1,blimarker2} do for k, j in pairs(bm) do .... end end Commented Feb 18, 2020 at 19:47

2 Answers 2

1

Function pairs() accepts only one argument of type table. You need a loop for each table:

for k,j in pairs(blipmarker1) do
  ...
end
for k,j in pairs(blipmarker2) do
  ...
end
Sign up to request clarification or add additional context in comments.

Comments

0

You could write your own stateful multipairs iterator. Consult Chapter 9.3 “Coroutines as Iterators” of Programming in Lua for more details: https://www.lua.org/pil/9.3.html

local function multipairs(tables)
    return coroutine.wrap(function()
        for _, t in pairs(tables) do -- Maybe you want ipairs here
            for k, v in pairs(t) do
                coroutine.yield(k, v)
            end
        end
    end)
end

local blipmarker1 = {
    { x = 10 , y = 5, z = 3 },
    { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
    { x = 100, y= 150, z=30 }
}

for _, j in multipairs{blipmarker1, blipmarker2} do
    print(j.x, j.y, j.z)
end

Comments

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.