Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using type() function to see if current string exist as table

Tags:

lua

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.

like image 571
Michelrandahl Avatar asked Mar 09 '11 18:03

Michelrandahl


1 Answers

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".

like image 179
interjay Avatar answered Oct 21 '22 19:10

interjay