Passing a 2d array to work in Lua

Is it possible to pass an array to a 2d function as a parameter? I have initialized the array like this:

tab={}
for i=1, 10 do
    tab[i]={}
    for z=1, 10 do
        tab[i][z]= 0
    end
end

      

and I have a function like this:

function foo(data)
    ...
    x = data[i][z] -- here i got error
    ...
end

      

An error message is given attempt to index field '?' (a nil value)

All variables are declared and initialized.

+2


source to share


3 answers


Your code should work if initialized correctly.

For example, the example below will output 3:



function foo(data)
  local i, z = 1, 2
  print(data[i][z])
end

local tab={}
for i=1, 10 do
  tab[i]={}
  for z=1, 10 do
    tab[i][z]= i + z
  end
end

foo(tab)

      

+4


source


Maybe you can share the rest of your code? The following runs without error:



tab={}
for i=1, 10 do
    tab[i]={}
    for z=1, 10 do
        tab[i][z]= 0
    end
end

function foo(data)
    print(data[3][2])
end

foo(tab)

      

+1


source


Given error message to index field '?' (nil value)

I got errors like this while changing the meta tag of some variable.

0


source







All Articles