Page 1 of 1

Dynamically call different child tables.

Posted: Fri Mar 16, 2012 8:47 pm
by Otoris
I have a table.

Code: Select all

tbl = {}
It has some child tables.

Code: Select all

tbl.a = 1
tbl.b = 2
tbl.c = 3
I have a function that sets and prints the table

Code: Select all

 
function tblscan()
    x = b
    print(tbl.x)
end
This currently returns nil. Any idea how to make this work without setting x = tbl.b?

Re: Dynamically call different child tables.

Posted: Fri Mar 16, 2012 9:05 pm
by trubblegum
What you're doing there does nothing.
I assume you're trying to do something like :

Code: Select all

t = {}
t.a, t.b, t.c = 1, 2, 3
function fetchvalue(x) return t[x] end

print fetchvalue('a')
It's usually called dynamic referencing.

You should probably read over this : http://lua-users.org/wiki/TablesTutorial
And look up function arguments too.

Re: Dynamically call different child tables.

Posted: Fri Mar 16, 2012 9:25 pm
by Otoris
Thanks for the helpful answer trubblegum!

Re: Dynamically call different child tables.

Posted: Fri Mar 16, 2012 10:48 pm
by Robin
That seems a bit unnecessary. Try this:

Code: Select all

 function tblscan()
    x = "b"
    print(tbl[x])
end

Re: Dynamically call different child tables.

Posted: Mon Mar 19, 2012 7:14 pm
by meoiswa
Are you tying to do something like this?

Code: Select all

table = {}
table.a = "The first"
table.b = "The third"
table.c = "Da fudge?"

function printThis(str)
    if table[str] then
        print(table[str])
    else
        print("There is no value at intex "..str.." in the table")
    end
end

printThis("a") -- > "The first"
printThis("c") -- > "Da fudge?"