Table Scope

I have the following (shortened)

1
2
3
4
5
6
7
8
9
main.lua
 
1.local objects = {}
2.local putobjects = require ("putmeinobjects")
 
putmeinobjects.lua
 
1.object = "testuser"
2.table.insert ( objects,  object )

you can use it like that, though i cant be sure if it good for you

main.lua

1
2
3
4
5
6
7
8
9
local obj = require("obj")
 
T = {}
 
obj.putintable()
 
for k,v in pairs(T) do
print(k,v)
end

thanx m8, will check it out ...

@riebesehl,

yes, you have declared objects as a *local* variable in the first module and you are expecting it to work in the second module. It is definitely out of scope.

as for examples, you have so many variables with the same names that as a beginner you will definitely face issues.

in your putmeinobjects.lua file

1
2
3
4
5
6
7
local theObjectTable = {}
 
function theObjectTable:addThisElement(thisElement)
    table.insert(theObjectTable, thisElement)
end
 
return theObjectTable

Hey Jayant, do you have how-to (or some sort of tutorial/lesson/write-up) on "k,v in pairs" thingy? I've seen it number of times in code snippets (and it's in my code too), but I sort of put it aside to figure out sometime later when I have time to seek out the answer. I don't like having things I don't quite understand in my code. So if you've already written something about it that I should read up on, I'd love to. (If you don't have anything already handy, it's okay. I'm sure I'll eventually stumble into it.)

@riebesehl, sorry, I didn't mean to change the subject, but I just saw the code snippet... and couldn't help myself.

Naomi

for k,v in pairs(table) is nothing fancy
its just "for" iterator for table
so explains like that: for every key and value in table do next function(it can be anything, printing their value and other table related things like "if table[i] == 0 then")

for professional explanation go here:
http://www.lua.org/pil/7.2.html

Hey Darkconsoles, thank you so much for the explanation and the link. I appreciate it, and I'll definitely read the write up on lua.org.

Naomi

you can do all sorts of funny things with this powerful feature, like that:

1
2
3
4
5
6
7
8
9
local T = {item1 = "one", item2 = "one", item3 = "two", item4 = "two"}
 
 
for k,v in pairs(T) do
        if v == "one" then
                v = "NOT ONE, BUT 10"
        end
        print(k,v)
end

Thank you, @darkconsoles! I'll definitely play around with it until I get a real feel for this. Thanks again!

Naomi

you're welcome) i found tables in lua are most interesting and most hard to learn things, i dont know why)

views:1375 update:2011/10/22 17:28:16
corona forums © 2003-2011