0

Suppose I have the following:

table = {a = {1, 2}, b = {3, 4}}
input = "a" -- abstracted away; it's a RV from another function.

You can use table.a[1] to get 1; however, I want to get it from the input variable - which is the return value of another function that I have, which returns the string "a" and not just a.

Now, this is where the error from here comes into play:

enter image description here

When I did table[input], it returned a table object, so then when I tried table[input][1], it had the calling a table error.

Is it possible to get 1 using indexing with the input "a"? If so, could someone let me know how this works? Thanks!

4
  • 1
    It simply is not possible to get an attempting to call table error with this. The only call expression/statement here is the print, which obviously is not a table. Commented Aug 27, 2022 at 17:43
  • Additionally, please format code using three backticks. Some reproducing steps would definitely be nice, because there aren't enough details. Commented Aug 27, 2022 at 17:45
  • 1
    try this table : table = {a = {1, 2}, b = {3, 4}, input = {5, 6} } and you will understand everything Commented Aug 27, 2022 at 18:01
  • Does this answer your question? Difference between t.foo and t[foo] in Lua Commented Aug 28, 2022 at 9:45

2 Answers 2

0

for any table if you use . to index it, it will use a string index.
When you use [] to index it, this means you can use any sort of datatype and it allows you to also use variables.

local someTable = {
    a = "hello",
    b = "world"
    c = "!"
}

-- I can do
print(someTable.a) -- prints "hello"

-- and
print(someTable["b"]) -- prints "world"

-- however
print(someTable[c]) -- will error since there is no c variable

------

-- note that this would be valid
local someVariable = "c"
print(someTable[someVariable]) -- prints "!"

Going back to your case. tbl1 is using [] and using the variable input. However tbl2 is using the string "input" as the index in your table. Your table does not contain "input" as a key, so it returns nil

Sign up to request clarification or add additional context in comments.

Comments

0

I hope I understand your question correctly, I apologize if not. If you want to, for example, send a specific part of a table to a user after they specified which key of the table they want then you're already doing everything correctly.

The tbl1 table contains the key "a" part of the main table. You can't print a table, but you can either print specific values by using tbl1[number] or do this:

table = {a = {1, 2}, b = {3, 4}}
input = "b"
tbl1 = table[input]

for _, v in pairs(table) do
    print(v)
end

-- Expected output:
-- 3
-- 4

Comments

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.