Calculator Community > Lua

Lua Accessing Array

(1/1)

Munchor:

--- Code: ---a = {1,2}
print(blocks[1])   --Should return "2", but returns "table: 0x1151460"
--- End code ---

I really don't know what the problem is here, how to return the index of an array? Thanks

Levak:
"blocks" ? Either I'm stupid, or I don't understand why you're trying to access to a nil table ...
In the case you wrote "a" instead of "blocks", it should return "1", not "2" because the Lua is in base 1 (contrary to C/C++/PHP/etc ... in base 0)

Munchor:

--- Quote from: Levak on June 20, 2011, 01:47:10 pm ---"blocks" ? Either I'm stupid, or I don't understand why you're trying to access to a nil table ...
In the case you wrote "a" instead of "blocks", it should return "1", not "2" because the Lua is in base 1 (contrary to C/C++/PHP/etc ... in base 0)

--- End quote ---

Oh my god, I'm so stupid, aren't I? Oh my god, I should really just get some sleep as wow, how did I miss that? Off to sleep, thanks.

Either way, check this out:


--- Code: ---a = {{1,2},{3,4}}

print(#a)


for i=0,i<(#a),i+1 do
print(a[i][0])
end
--- End code ---

I get as output:


--- Code: ---2
lua: testing.lua:8: attempt to compare nil with number
stack traceback:
testing.lua:8: in main chunk
[C]: ?

--- End code ---

i=0, number
#a,  number
i+1,  number (I don't even have to set this, as it's default, but I get the same error when I don't put it)

What's wrong here, then? Thanks.

Levak:
As the error says, you're trying to do a [C] for loop

In lua, it is :

for var = initial_value, end_value, [increment] do

like :


--- Code: ---a = {{1,2},{3,4}}

print(#a)


for i=0, #a do
print(a[i][0])
end

--- End code ---

but it is cleverest to do :


--- Code: ---a = {{1,2},{3,4}}

print(#a)


for i, var in ipairs(a) do
print(i.." : "..var)
end

--- End code ---

Navigation

[0] Message Index

Go to full version