Help With Table Logic

I am confused and in dire need of some help on this.

I know that in LUA properties are dynamic and can be added to just about any object at any time.

So I creating a Quiz Table and trying to do the following assignment.
But I get an error "attempt to index field '?'"
Can't we add properties to Table Items?

1
2
3
4
local myTable = {}
for loopCount=1,7 do
    myTable[loopCount].myID = loopCount
end

I am not 100% sure what you are trying to do, but I will give it a crack. If you say

local myTable

you create a variable with value nil. If you say

local myTable = {}

you create an empty table, and set myTable to reference it.
if you say

myTable.gack = "Ack"

you are creating a table element named gack with the value "Ack"

In the loop, if you say

myTable[loopCount] = loopCount

you creating an element whose name is the value of loopCount, and whose value is the value of loopCount. The [] treats the table like an array. If you say

myTable[loopCount].myID = loopCount

when loopCount is 1, you are telling it to set element myID of element 1 of myTable to loopCount. Or myTable.1.myID Since that does not exist, you get an error.

I think what you want is an array(table) of tables. Take a look at this (I put in a simple table printer to help show what is going on.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
---------------------------------------
function printTable( t ) -- Table ref
 
        print("-- "..tostring(t).." --")
        for k,v in pairs(t) do
                print("ELEMENT "..tostring(k).." VALUE "..tostring(v).." TYPE IS "..type(v))
        end
 
        print("---------------------")
end
 
local myTable = {}
myTable.gack = "Ack"
 
for loopCount=1,4 do
   --myTable[loopCount].myID = loopCount  -- nil field value
    
   --myTable[loopCount] = loopCount   -- Value = index
        
   -- Table of tables --
   myTable[loopCount] = {}  -- New tabled referenced by myTable[loopCount]
   myTable[loopCount].myID = loopCount
   myTable[loopCount].myIDPlusOne = loopCount + 1
end
 
printTable(myTable)
printTable(myTable[1])

not an expert in Lua, but I think the problem is you are trying to add attributes to something that hasn't yet been defined/created.

also not in front of my coding computer, but I think this will work...

local myTable = {}
for loopCount=1,7 do
myTable[loopCount] = {} -- or just define myTable[loopCount] as something, a display object etc..
-- then add the attribute
myTable[loopCount].myID = loopCount
end

views:1317 update:2011/9/27 18:14:54
corona forums © 2003-2011