tags:

views:

401

answers:

5

It is possible to pass 2d array to a function as a paramter ? I initialized an 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 function like this :

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

The gave the error message attempt to index field '?' (a nil value)

All variables are declared and initialized.

A: 

In your function foo, are i and z numbers?

RCIX
+4  A: 

Your code should work if it is initialized properly.

For example, the below code sample 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)
Nick D
Note that it is good idea to make i and z local variables.
Alexander Gladysh
+1  A: 

Maybe you can share the rest of your code? The following runs with no 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)
mirven
A: 

The gave the error message attempt to index field '?' (a nil value)

I got such errors while changing metatable of some variable.

AlexeyBor
A: 

I get the "attempt to index field '?' (a nil value)" error message too. I'm not sure lua can do 2D arrays

Ben