Omnimaga

Calculator Community => TI Calculators => Lua => Topic started by: Munchor on June 20, 2011, 01:25:59 pm

Title: Lua Accessing Array
Post by: Munchor on June 20, 2011, 01:25:59 pm
Code: [Select]
a = {1,2}
print(blocks[1])   --Should return "2", but returns "table: 0x1151460"

I really don't know what the problem is here, how to return the index of an array? Thanks
Title: Re: Lua Accessing Array
Post by: 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)
Title: Re: Lua Accessing Array
Post by: Munchor on June 20, 2011, 03:28:52 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)

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: [Select]
a = {{1,2},{3,4}}

print(#a)


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

I get as output:

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

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.
Title: Re: Lua Accessing Array
Post by: Levak on June 20, 2011, 03:49:12 pm
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: [Select]
a = {{1,2},{3,4}}

print(#a)


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

but it is cleverest to do :

Code: [Select]
a = {{1,2},{3,4}}

print(#a)


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