1

I have a table logTable = {["cdm"] = "log text", ["data_engine"] = "log text"}

The code:

for k,v in pairs(logTable) do
    print(v["cdm"]) end

Gives the desired result: log text

However

print(logTable["cdm"])

returns nothing. What am I doing wrong here?

EDIT:

So this is actually how I am making the table:

table.insert(logTable, { [probeName] = file.read('export/'..robotName..'/probes/'..probeGroup..'/'..probeName..'/'..probeName..'.log')})    

Where probeName is a variable, could it be that I need to ["probeName"] to make it a string? However this takes it as a literal and not a variable?

How can I use a variable as table index/key

2
  • 1
    Your example code works fine. codepad.org/n8z78Bae There must be something different going on in your actual code? Commented Jul 6, 2012 at 9:19
  • So this is actually how I am making the table: table.insert(logTable, { [probeName] = file.read('export/'..robotName..'/probes/'..probeGroup..'/'..probeName..'/'..probeName..'.log')}) Where probeName is a variable, could it be that I need to ["probeName"] to make it a string? However this takes it as a literal and not a variable? How can I use a variable as table index/key Commented Jul 6, 2012 at 9:24

1 Answer 1

2

You actually have a table inside a table here, so your table looks like this:

{
    { 
      ["cdm"] = "log text",
      ["data engine"] = "log text"
    }
}

That's why your print(logTable["cdm"]) doesn't work. table.insert is also meant to be used with number-indexed tables; this time, the dictionary syntax is clearer:

logTable["probeName"] = file.read('export/'..robotName..
                                  '/probes/'..probeGroup..'/'
                                  ..probeName..'/'..probeName..'.log')
Sign up to request clarification or add additional context in comments.

1 Comment

In the latter case logTable["probeName"] can be also written as logTable.probeName. Unless you actually want to use the value of probeName variable, in which case you should use just logTable[probeName].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.