This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
shournk's profile picture

Using variable inside a table reference?

Started by shournk, 23 May 2014 - 02:03 AM
shournk #1
Posted 23 May 2014 - 04:03 AM
I am trying to refer to a subtable


if table.subtable1.state then
    do something
end

And I want to refer to subtable1 using a variable passed by an above function.



local function(KEY)
    if table.KEY.state then
        do something
    end
end

But it seems to always try and access the table literally as table.key (which doesn't exist). How do I do this?
KingofGamesYami #2
Posted 23 May 2014 - 04:23 AM
Instead of table.key which will access literally "key", use table[key]. Since table.key == table["key"], you have to use the brackets.
flaghacker #3
Posted 23 May 2014 - 11:10 AM
I am trying to refer to a subtable


if table.subtable1.state then
	do something
end

And I want to refer to subtable1 using a variable passed by an above function.



local function(KEY)
	if table.KEY.state then
		do something
	end
end

But it seems to always try and access the table literally as table.key (which doesn't exist). How do I do this?

There's something wrong in your function:

local function(key)
has to be

local foo = function(key)
or

local function foo(key)
Edited on 23 May 2014 - 09:13 AM
CometWolf #4
Posted 23 May 2014 - 06:57 PM
Not really wrong per say, a function without a name is simply an anonymous function. Although in this case he dosen't appear to be calling it or using it as an argument, so it is somewhat pointless. Probably just meant as an example though.
flaghacker #5
Posted 23 May 2014 - 08:02 PM
Not really wrong per say, a function without a name is simply an anonymous function. Although in this case he dosen't appear to be calling it or using it as an argument, so it is somewhat pointless. Probably just meant as an example though.

Ok, I founded it confusing at first… But oh well…