开发者

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

开发者 https://www.devze.com 2023-02-16 00:33 出处:网络
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 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
开发者_C百科

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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消