17

Is it possible to see if a string is the same as the name of a table?

For example: I know that a table called 'os' exists, and I have a string "os". Is there then a way to do this:

x="os"
if type(x)=="table" then
    print("hurra, the string is a table")
end

Of course this example wont work like I want it to because

type(x)

will just return "string".

The reason why I want to do this, is just because I wanted to list all existing Lua tables, so I made this piece of code:

alphabetStart=97
alphabetEnd=122

function findAllTables(currString, length)

    if type(allTables)=="nil"   then
        allTables={}
    end

    if type(currString)=="table" then
        allTables[#allTables+1]=currString
    end

    if #currString < length then
        for i=alphabetStart, alphabetEnd do
            findAllTables(currString..string.char(i), length)
        end
    end
end

findAllTables("", 2)

for i in pairs(allTables) do
    print(i)
end

I wouldn't be surprised if there is an easier method to list all existing tables, I'm just doing this for fun in my progress of learning Lua.

RBerteig
  • 41,948
  • 7
  • 88
  • 128
Michelrandahl
  • 3,365
  • 2
  • 26
  • 41

2 Answers2

19

If you want to iterate over all global variables, you can use a for loop to iterate over the special _G table which stores them:

for key, value in pairs(_G) do
    print(key, value)
end

key will hold the variable name. You can use type(value) to check if the variable is a table.

To answer your original question, you can get a global variable by name with _G[varName]. So type(_G["os"]) will give "table".

iono
  • 2,575
  • 1
  • 28
  • 36
interjay
  • 107,303
  • 21
  • 270
  • 254
4

interjay gave the best way to actually do it. If you're interested, though, info on your original question can be found in the lua manual. Basically, you want:

mystr = "os"

f = loadstring("return " .. mystr);

print(type(f()))

loadstring creates a function containing the code in the string. Running f() executes that function, which in this case just returns whatever was in the string mystr.

usul
  • 784
  • 5
  • 16