0

in Lua, I have a large number of tables named A-Z (I referenced just 2 below). I have a function NextVar(PreviousVar) which I use to cycle the output from A-Z. but when I try to print a value from a table (A[1] for example), it prints nil instead. How can I transform the return value from the function into a usable variable?

A = {10, 33, 35}
B = {15, 55, 45}

local alphabet = "1ABCDEFGHIJKLMNOPQRSTUVWXYZ"

function NextVar(PreviousVar)
    local index = string.find(alphabet, PreviousVar)
    if index then
        index = (index % #alphabet) + 1 -- move to next letter, wrapping at end
        return alphabet:sub(index, index)    
    end
end

PreviousVar = "1"

repeat
    if NextVar(PreviousVar) != nil then
        x = NextVar(PreviousVar)
        print(x)  -- works as it prints A,B,C,D, etc
        print(x[1])  -- just prints nil
        PreviousVar = NextVar(PreviousVar)
    end
until PreviousVar == nil```

1 Answer 1

2

NextVar returns strings. "A", "B", ...

Why do you expect x[1] to be a value of table A? There is no relation between the string "A" and the table A.

If you want to refer to those tables using the return values of NextVar you can use the global environment table _G. _G[x][1] will return the first element of A for x being "A"

Usually you would just have a table of tables rather than accessing global tables through their names.

local myTables = {
  {10, 33, 35},
  {15, 55, 45},
}

for i,v in ipairs(myTables) do
  print(i)
  print(v[1])
end
Sign up to request clarification or add additional context in comments.

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.