Using the type () function to see if the current row exists as a table

Can I see if a row matches a table name?

For example: I know that there is a table named "os" and I have the string "os" . Is there any way to do this:

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

Of course, this example does not work as I want, because

 type(x) 

just return the string.

The reason I want to do this is only because I want to list all the 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 would not be surprised if there is an easier way to list all the existing tables, I just do it for fun in the Lua learning process.

+8
lua
source share
2 answers

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

 for k,v in pairs(_G) do print (k,v) end 

k will contain the name of the variable, and v will contain the value, so you can use type(v) to check if the variable is a table.

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

+14
source share

interjay gave a better way to do this. If you're interested, information about 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 () performs this function, which in this case simply returns everything that was in the string mystr.

+3
source share

All Articles