Dynamically call different child tables.

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Otoris
Prole
Posts: 5
Joined: Thu Mar 15, 2012 6:38 am

Dynamically call different child tables.

Post 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?
User avatar
trubblegum
Party member
Posts: 192
Joined: Wed Feb 22, 2012 10:40 pm

Re: Dynamically call different child tables.

Post 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.
User avatar
Otoris
Prole
Posts: 5
Joined: Thu Mar 15, 2012 6:38 am

Re: Dynamically call different child tables.

Post by Otoris »

Thanks for the helpful answer trubblegum!
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Dynamically call different child tables.

Post by Robin »

That seems a bit unnecessary. Try this:

Code: Select all

 function tblscan()
    x = "b"
    print(tbl[x])
end
Help us help you: attach a .love.
meoiswa
Prole
Posts: 48
Joined: Wed Mar 14, 2012 8:13 pm
Location: Venezuela

Re: Dynamically call different child tables.

Post 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?" 
Write the ö of Löve with Alt+numPad(148) or Alt+numPad(153)
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 2 guests