Author Topic: Lua Accessing Array  (Read 3926 times)

0 Members and 2 Guests are viewing this topic.

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Lua Accessing Array
« 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

Offline Levak

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1002
  • Rating: +208/-39
    • View Profile
    • My website
Re: Lua Accessing Array
« Reply #1 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)
I do not get mad at people, I just want them to learn the way I learnt.
My website - TI-Planet - iNspired-Lua

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Re: Lua Accessing Array
« Reply #2 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.
« Last Edit: June 20, 2011, 03:32:16 pm by Scout »

Offline Levak

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1002
  • Rating: +208/-39
    • View Profile
    • My website
Re: Lua Accessing Array
« Reply #3 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
« Last Edit: June 20, 2011, 03:51:18 pm by Levak »
I do not get mad at people, I just want them to learn the way I learnt.
My website - TI-Planet - iNspired-Lua