Lua 使用type()函数查看当前字符串是否作为表存在
是否可以查看字符串是否与表名相同 例如: 我知道存在一个名为“os”的表,我有一个字符串Lua 使用type()函数查看当前字符串是否作为表存在,lua,Lua,是否可以查看字符串是否与表名相同 例如: 我知道存在一个名为“os”的表,我有一个字符串“os”。 那么有没有办法做到这一点: x="os" if type(x)=="table" then print("hurra, the string is a table") end 当然,这个例子不会像我希望的那样工作,因为 type(x) 将只返回“string” 我之所以要这样做,是因为我想列出所有现有的Lua表,所以我编写了以下代码: alphabetStart=97 alphabet
“os”
。
那么有没有办法做到这一点:
x="os"
if type(x)=="table" then
print("hurra, the string is a table")
end
当然,这个例子不会像我希望的那样工作,因为
type(x)
将只返回“string”
我之所以要这样做,是因为我想列出所有现有的Lua表,所以我编写了以下代码:
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
alphabetStart=97
alphabetEnd=122
函数findAllTables(currString,length)
如果类型(所有表)=“nil”,则
allTables={}
结束
如果类型(currString)=“表”,则
allTables[#allTables+1]=currString
结束
如果#currString<长度,则
对于i=alphabetStart,alphabetEnd do
findAllTables(currString..string.char(i),长度)
结束
结束
结束
findAllTables(“,2)
因为我是成对的(所有表格)做的
印刷品(一)
结束
如果有一种更简单的方法列出所有现有的表,我不会感到惊讶,我这样做只是为了在学习Lua的过程中获得乐趣。如果您想迭代所有全局变量,可以使用
for
循环迭代存储它们的特殊\G
表:
for key, value in pairs(_G) do
print(key, value)
end
键
将保存变量名。您可以使用type(value)
检查变量是否为表
要回答最初的问题,可以使用
\u G[varName]
按名称获取全局变量。因此类型(_G[“os”])
将给出“table”
interjay给出了实际执行的最佳方法。但是,如果您感兴趣,可以在中找到有关原始问题的信息。基本上,你想要:
mystr = "os"
f = loadstring("return " .. mystr);
print(type(f()))
loadstring创建一个包含字符串中代码的函数。运行f()执行该函数,在本例中,该函数只返回字符串mystr中的任何内容。太棒了,非常感谢。知道必须有一个简单的方法来做到这一点:)