使用type()函数查看当前字符串是否存在于表中。

有没有办法判断一个字符串是否与表的名称相同?

例如: 我知道有一个名为'os'的表,我有一个字符串“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

我不会感到惊讶,如果有一个更简单的方法来列出所有现有的表,我只是在学习Lua的过程中为乐趣而做这个。

原文链接 https://stackoverflow.com/questions/5250374

点赞
stackoverflow用户189205
stackoverflow用户189205

如果您想遍历所有全局变量,可以使用 for 循环遍历存储它们的特殊 _G 表:

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

key 将持有变量名。您可以使用 type(value) 来检查变量是否为表格。

回答您的原始问题,您可以通过名称使用 _G[varName] 获取全局变量。因此,type(_G["os"]) 将返回 "table"

2011-03-09 18:38:28
stackoverflow用户658176
stackoverflow用户658176

interjay 提供了实际操作的最佳方法。但如果您有兴趣,可以在 lua 手册 中找到有关您原来问题的信息。基本上,您需要:

mystr = "os"

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

print(type(f()))

loadstring 创建一个包含字符串中代码的函数。运行 f() 执行该函数,这里返回的是字符串 mystr 中的任何内容。

2011-03-14 03:43:40